角5
当服务被创建和销毁时,它的生命周期挂钩(如果有的话)是什么,以及它的数据如何在组件之间共享?
编辑:为了澄清,这是而不是关于组件生命周期的问题。这个问题与服务的生命周期有关。如果服务没有生命周期,那么如何管理组件和服务之间的数据流?
发布于 2018-04-27 06:37:24
服务可以有两个作用域。
如果在您的模块上声明了服务,那么您的所有实例都是共享的,这意味着在创建第一个需要它的组件/指令/服务/管道时,将构建服务。然后,当模块本身被销毁时,它将被销毁(大多数情况下,当页面被卸载时)
如果在组件/指令/管道上声明服务,则每次创建组件/指令/管道时将创建一个实例,当相关组件/指令/管道被销毁时,将销毁该服务。
代码测试:两个服务用于显示创建/销毁它们的时间。
@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');
}
}如您所见,角中的Service可以有OnDestroy生命周期挂钩。
发布于 2021-05-11 01:51:44
OnDestroy适用于正式文档:https://angular.io/api/core/OnDestroy中所述的服务。
引用:
在销毁指令、管道或服务时调用的生命周期挂钩。用于在实例被销毁时需要进行的任何自定义清理。
https://stackoverflow.com/questions/50056446
复制相似问题