angularangular-servicesinstanceid

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


I am using a service across multiple components, each provided to the component in its own providers array.

I am curious to see which components are using which instances of the service, as I am doing some experiments that involve passing them around.

Is there any built in way for me to access an id for the service instance that is created? For example, what would replace the ?? in the code snippet below?

@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...' + '??');
    }

Solution

  • There isn't a dependency injection feature to query the instance ID of a reference. Some DI frameworks have this feature, but Angular doesn't.

    So I use a static counter.

    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++;
         }
    }
    

    It would be nice if Angular would tag services with a this._id$ unique value or something for us. I'm sure it would be one line of code somewhere.