服务可以有 2 个作用域。
如果在您的模块上声明了服务,则您将共享相同的实例,这意味着将在创建第一个需要它的组件/指令/服务/管道时构建服务。然后在Module本身被销毁的时候就被销毁(大部分是在页面卸载的时候)
如果服务声明在Component/Directive/Pipe上,则每次创建Component/Directive/Pipe时会创建1个实例,销毁相关的Component/Directive/Pipe时会销毁。
You can see it in action
代码测试:2 个服务用于显示它们何时被创建/销毁。
@NgModule({
providers: [GlobalService] // This means lifeCycle is related to the Module, and only one instance is created for the whole module. It will be created only when the first element who needs it will be created.
})
export class AppModule { }
第二个服务是一个本地组件服务,将为每个创建的hello-component 实例创建,并将在hello-component 被销毁之前销毁。
@Injectable()
export class LocalService implements OnDestroy{
constructor() {
console.log('localService is constructed');
}
ngOnDestroy() {
console.log('localService is destroyed');
}
}
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers: [LocalService]
})
export class HelloComponent implements OnInit, OnDestroy {
@Input() name: string;
constructor(private localService: LocalService, private globalService: GlobalService) {}
ngOnInit(){
console.log('hello component initialized');
}
ngOnDestroy() {
console.log('hello component destroyed');
}
}
如您所见,angular 中的Service 可以有OnDestroy 生命周期钩子。