Angular 5
服务是在什么时候创建和销毁的,它的生命周期挂钩是什么(如果有的话),它的数据是如何在组件之间共享的?
EDIT:澄清一下,这是一个关于组件生命周期的问题.这个问题与服务的生命周期有关.如果服务没有生命周期,如何管理组件和服务之间的数据流?
Angular 5
服务是在什么时候创建和销毁的,它的生命周期挂钩是什么(如果有的话),它的数据是如何在组件之间共享的?
EDIT:澄清一下,这是一个关于组件生命周期的问题.这个问题与服务的生命周期有关.如果服务没有生命周期,如何管理组件和服务之间的数据流?
服务可以有2个作用域.
如果在您的模块上声明了服务,那么您将为所有人共享相同的实例,这意味着服务将在创建需要它的第一个组件/指令/服务/管道时被构造.然后,当模块本身被销毁时,它将被销毁(大多数情况下,当页面被卸载时)
如果服务是在组件/指令/管道上声明的,那么每次创建组件/指令/管道时将创建一个实例,并在销毁相关组件/指令/管道时销毁一个实例.
代码测试:制作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');
}
}
如您所见,Service
英寸的Angular 可以有OnDestroy
个生命周期钩子.