是否可以获取服务的实例 ID?

Is it possible to obtain an instance Id for a service?

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

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

是否有任何内置方法可以让我访问所创建的服务实例的 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...' + '??');
    }

没有依赖注入功能来查询引用的实例 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$ 独特价值或其他东西的服务,那就太好了。我确定它会是某处的一行代码。