1

我正在使用跨多个组件的服务,每个组件都在其自己的提供程序数组中提供给组件。

我很想知道哪些组件正在使用服务的哪些实例,因为我正在做一些涉及传递它们的实验。

是否有任何内置方法可以让我访问创建的服务实例的 ID?例如,??下面的代码片段中的替换是什么?

@Component({
    selector: 'app-component1',
    templateUrl: './component1.component.html',
    providers: [SearchService]
})
export class Component1 {

    constructor(
        public searchService: SearchService,
    ) {
        console.log('The instance Id of searchService is...' + '??');
    }
4

1 回答 1

3

没有依赖注入功能来查询引用的实例 ID。一些 DI 框架具有此功能,但 Angular 没有。

所以我使用静态计数器。

constructor(public searchService: SearchService) {
    console.log('The instance Id of searchService is...' + searchService.id);
}

@Injectable()
export class SearchService {
     private static nextId: number = 0;
     public id: number;
     constructor() {
         this.id = SearchService.nextId++;
     }
}

如果 Angular 能为我们的服务标记一个this._id$独特的价值或其他东西,那就太好了。我敢肯定它会是某处的一行代码。

于 2018-07-30T21:10:40.297 回答