typescript - How to parameterize an injectable service in Angular 2 -


i have service core of framework incorporated many projects. saves data local storage key static. make key instead passed in parameter can unique every project. because when i'm testing localhost:4200 on of these projects there conflict local storage field/key. have is:

@injectable() export class myservice {  private static readonly storage_id = 'model-data';       constructor(  ) {      }      somefunction() {         localstorage.setitem(myservice.storage_id, json.stringify(this._model))     }  } 

how can add parameter constructor can still instantiated through angular 2 dependency injection?

you provide constructor parameter key:

export const storage_key = new injectiontoken<string>('storagekey');  @injectable() export class myservice {   constructor(@inject(storage_key) private storagekey: string) { }    ... } 

then in providers need supply value it:

providers: [   { provide: storage_key, usevalue: 'this-app-key' },   myservice,   ... ] 

an example given in di documentation.


alternatively, create factory provider function:

export function createservicefactory(storagekey: string) {     return () => new myservice(storagekey); } 

and use that:

{ provide: myservice, usefactory: createservicefactory('that-app-key') } 

this way don't need @inject parameter.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -