在Angular中,可以使用Injector
类来检查一个注入的服务是否为该服务的“全局”实例。下面是一个示例代码:
首先,创建一个SharedService
服务,其中包含一个计数器属性和一个增加计数器的方法:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
counter = 0;
increment() {
this.counter++;
}
}
然后,在需要检查服务是否为全局实例的组件中,注入Injector
类,并使用它来获取SharedService
的实例:
import { Component, Injector } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
constructor(private injector: Injector) {}
checkService() {
// 通过 Injector 获取 SharedService 的实例
const sharedService = this.injector.get(SharedService);
// 检查获取的实例是否为全局实例
if (sharedService instanceof SharedService) {
console.log('Service is a global instance');
} else {
console.log('Service is not a global instance');
}
}
}
在上面的代码中,我们通过创建一个Injector
实例,并使用get()
方法从该实例中获取SharedService
的实例。然后,我们使用instanceof
运算符来检查获取的实例是否为SharedService
类的实例。如果是,则说明它是全局实例,否则不是。
请注意,Injector
类是通过constructor
方法注入的,因此需要在组件的构造函数中声明它。此外,SharedService
也必须在模块的providers
数组中声明,以便被注入和使用。
希望以上代码能帮助到你!