- 当
Service A
被声明在Moudule
里时,模块里所有组件、管道、指令拥有同一个Service A
的实例,当第一个需要注入该Service A
的组件、管道、指令实例化A
后,后面再需要注入Service A
时,用的是同一个实例。当Moudle
被销毁(通常是该模块的页面被卸载)后,Service A
同步被销毁。 - 当
Service A
被声明在组件、指令、管道中时,每一次组件、指令、管道需要注入Service A
时都会创建一个单独的A
实例,当该组件、指令、管道被销毁时,A
实例同步被销毁。
// 第一种情况
@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 { }
// 第二种情况
@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');
}
}
参考: What is the lifecycle of a service in Angular 5
标签:销毁,console,log,Service,组件,Angular From: https://www.cnblogs.com/lhjc/p/17664104.html