Angular 7,不同模块中的服务实例不同?

时间:2019-04-30 12:02:07

标签: angular angular7 angular-services

在angular 7应用程序中,我具有带有装饰器@Injectable()的服务(test.service),(不包含ProvideIn),但app.module中未提供它,我也有2种模块:client.modulecore.module。当我在两个模块的提供程序中都添加test.service,然后在客户端的组件和核心的组件中注入test.service时,我得到了test.service的1个实例,但我希望得到2个实例。

问题1:为什么会这样?

问题2:如何在不同的模块中拥有不同的服务实例?

测试服务:

import { Injectable } from '@angular/core'

@Injectable()
export class TestService {
  public bla = 1

  constructor() {
    console.log('Created')
  }

}

客户端模块:

@NgModule({
  declarations: [
    ClientComponent
  ],
  imports: [
    CommonModule
  ],
  providers: [TestService]
})

核心模块:

    @NgModule({
      declarations: [
        coreComponent
      ],
      imports: [
        CommonModule
      ],
      providers: [TestService]
    })

客户端组件:

export class ClientComponent implements OnInit {

   constructor(private ts: TestService) {}

}

核心组件:

export class ClientComponent implements OnInit {
   constructor(private ts: TestService)
}

0 个答案:

没有答案