Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a string into a service factory?

I'm trying to inject a string into a service factory, but am running into error TS1206: Decorators are not valid here.

I'm using the following code -

export let serviceFactory = (http: Http, @Inject('TEMPLATE') template: string) => {
    return new Service(http, template);
}

I use my factory like so -

export let serviceProvider = {
    provide: Service,
    useFactory: serviceFactory,
    deps: [Http]
};

How can I inject a string in a service factory?

like image 225
onetwothree Avatar asked May 11 '17 12:05

onetwothree


1 Answers

app.module.ts

export let serviceFactory = (http: Http, template: string) => {
  return new Service(http, template);
}

export let serviceProvider = {
  provide: Service,
  useFactory: serviceFactory,
  deps: [Http, [new Inject('TEMPLATE')]]
};

@NgModule({
  imports: [
    BrowserModule,
    HttpModule 
  ],
  declarations: [ AppComponent ],
  providers: [
    { provide: 'TEMPLATE', useValue: 'test' },
    serviceProvider,
  ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

service.ts

@Injectable()
export class Service {
  constructor(private http: Http, @Inject('TEMPLATE') template: string) {
      console.log(template);
  }
}

Plunker Example

like image 123
yurzui Avatar answered Oct 12 '22 23:10

yurzui