Angular 5
服务何时创建和销毁,它的生命周期 Hook 是什么(如果有)以及它的数据如何在组件之间共享?
编辑:澄清一下,这不是关于组件生命周期的问题。这个问题是关于服务的生命周期。如果服务没有生命周期,如何管理组件和服务之间的数据流?
最佳答案
服务可以有 2 个作用域。
如果在您的模块上声明了服务,那么您将拥有为所有人共享的相同实例,这意味着将在创建需要它的第一个组件/指令/服务/管道时构建服务。然后在 Module 本身销毁时销毁它(大部分时间是在页面卸载时)
如果服务声明在Component/Directive/Pipe上,那么每次创建Component/Directive/Pipe时都会创建1个实例,并在销毁相关Component/Directive/Pipe时销毁。
代码测试:制作了 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
生命周期钩子(Hook)。
关于angular - Angular 5 中服务的生命周期是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50056446/