如何将字符串注入服务工厂? [英] How can I inject a string into a service factory?

查看:55
本文介绍了如何将字符串注入服务工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串注入服务工厂,但是遇到错误TS1206: Decorators are not valid here.

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

我正在使用以下代码-

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?

推荐答案

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

这篇关于如何将字符串注入服务工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆