Ole
Ole

Reputation: 46910

Passing arguments to the constructor of an @Injectable in Angular?

Suppose we have an @Injectable class like this:

interface IServiceConfig {
    boo: string;
    foo: string;
}

@Injectable()
class Service {
    boo: string = "boo";
    foo: string = "foo";

    constructor(IServiceConfig isc) {
       Object.assign(this, isc);
    }
}

Is it possible to pass an IServiceConfig instance to the constructor of Service while still allowing Angular to create and inject the Service instance?

Is there a different way to configure Services prior to Angular creating instances of them?

Upvotes: 2

Views: 1795

Answers (1)

mahi-man
mahi-man

Reputation: 4676

This is untested, but you should be able to do like this:

import { Injectable, Inject, Optional } from '@angular/core';

interface IServiceConfig {
    boo: string;
    foo: string;
}

@Injectable()
class Service {
    boo: string = "boo";
    foo: string = "foo";

    constructor(@Inject('isc') @Optional() public isc?: IServiceConfig ) {
       Object.assign(this, isc);
    }
}

An in your providers (e.g. in app.module):

providers: [
    {provide: 'isc', useValue: {boo: 'hoo', foo: 'bar'},
...

Upvotes: 3

Related Questions