BBaysinger
BBaysinger

Reputation: 6987

How to parameterize an injectable service in Angular 2

I have a service as the core of a framework that will we be incorporated into many projects. It saves some data to local storage with a key that is currently static. I would like to make the key instead passed in as a parameter so it can be unique for every project. This is because when I'm testing from localhost:4200 on any of these projects there is a conflict with that local storage field/key. What I 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 I add a parameter to the constructor so it can still be instantiated through Angular 2 dependency injection?

Upvotes: 1

Views: 138

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121966

You could provide a constructor parameter for the key:

export const STORAGE_KEY = new InjectionToken<string>('storageKey');

@Injectable()
export class MyService {
  constructor(@Inject(STORAGE_KEY) private storageKey: string) { }

  ...
}

Then in your providers you need to supply a value for it:

providers: [
  { provide: STORAGE_KEY, useValue: 'this-app-key' },
  MyService,
  ...
]

An example is given in the DI documentation.


Alternatively, create a factory provider function:

export function createServiceFactory(storageKey: string) {
    return () => new MyService(storageKey);
}

and use that:

{ provide: MyService, useFactory: createServiceFactory('that-app-key') }

This way you don't need to @Inject the parameter.

Upvotes: 5

Related Questions