How to use providers in a service?

I need use multiple instances of one service.

Usually when I use one instance of this service in component, I write like this:

@Component({
    selector: 'one-component',
    providers: [provide("token1", {useClass: Service})],
    template: `
        <h1>App</h1>
    `
})
export class OneComponent {
    constructor(@Inject('token1') service:Service) {}
}

But now I need use this service in Service2, I write like this:

export class Service2 {
    constructor(@Inject('token1') service:Service) {}
}

As you know, it shows:

No provider

Because Service2 does not have providers: [provide("token1", {useClass: Service})] . But where can I add it since it does not have @Component ?

Thanks


目前不支持以这种方式配置服务,目前还没有计划添加支持https://github.com/angular/angular/issues/5622


I don't think Gunter's answer is fully correct here. If I understood Hongbo Miao's issue correctly, this can be "easily" achieve. If you want to get a new instance of a service on every injection you'd have to use useFactory instead of useClass provider configuration.

Then if you get a no provider error for "token1" in Service2 it's because it's not configure on the right injector, sibling or parent of OneComponent ... where Service2 is injected.

Edit:

For this to work you would have to define your Service and Service2 provider at the root component (for instance). In this case, all will share the same instance of the services.

If you want to have different instances in each components, then define the providers at the component level, where the services are being used.

@Component({
  providers: [Service, Service2],
  // Other config props
})
export class RootComponent {
}

@Component({
  // Config props
})
export class OneComponent {
  constructor(public service: Service) {}
  methodx() {
    this.service...
  }
}

@Component({
  // Config props
})
export class TwoComponent {
  constructor(public service: Service2) {}
  methodx() {
    this.service...
  }
}

@Injectable()
export class Service2 {
  constructor(public service: Service) {
  }
}

Using the @Inject('StringToken') is not the best thing you do and is not the recommended way. Use Type token instead (as done in the code above).

Resources:

  • http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
  • http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

  • 我已经通过在app.module.ts的提供程序数组中声明这两个服务来纠正此错误(将服务B用于服务A)。

    @NgModule({
        declarations: [...],
        imports:      [...],
        providers:    [
            ServiceA,
            ServiceB,
        ],
        bootstrap:    [...],
    })
    
    链接地址: http://www.djcxy.com/p/32510.html

    上一篇: 触摸屏设备上的WPF AutomationPeer崩溃

    下一篇: 如何在服务中使用提供者?