Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 inject service to Utilities class

Tags:

angular

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?

like image 745
Batsheva Avatar asked Oct 30 '22 06:10

Batsheva


1 Answers

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?

like image 188
Yonatan Lilling Avatar answered Dec 11 '22 14:12

Yonatan Lilling