5

I have a Utilities class with some static methods on it.

In one method I want to get an object and return a safe style of its image.

The issue is I need to use the DomSanitizer service, and I am unable to use it in static method. Here is the code:

export class Utilities{ constructor(private sanitizer:DomSanitizer){ } static getImageStyle(obj){ return this.sanitizer.bypassSecurityTrustStyle(`url(data:image/jpg;base64,${obj.image})`); } } 

Does this need to be done in a non-static method and I should create instance of the class every time I use this function?

2 Answers 2

2

as you can see here static functions do not use the instance of the class. there for if you declare a service in the constructor it wont be available in static methods.

why not just make Utilities also a service and add sanitizer:DomSanitizer to the utilies service constructor like you did?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you are right. I guess I will need to do it as a service. I wanted to avoid it as I already used this Utilities in many places...
0

you can pass Injector to the static function as a parameter and then use injector.get() to get instance of DomSanitizer.

https://angular.io/guide/dependency-injection#appendix-working-with-injectors-directly

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.