在上一篇文章中,我对服务的作用及创建使用稍作介绍。那么,问题来了,在服务中 这个公共领域,如果其属性值发生变化,那我们如何将其更新到组件中呢?
首先,你需要了解Angular的完整生命周期,对应的生命周期钩子的作用是什么,都分别在什么时候触发。
lifecycle.components.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from "../../services/user/user.service";@Component({selector: 'app-lifecycle',templateUrl: './lifecycle.component.html',styleUrls: ['./lifecycle.component.scss'],providers: [ UserService ]
})export class LifeCycleComponent implements OnInit {constructor(public user: UserService) {}ngOnChanges(): void {}ngOnInit(): void {}ngDoCheck(): void {}ngAfterContentInit(): void {}ngAfterContentChecked(): void {}ngAfterViewInit(): void {}ngAfterViewChecked(): void {}ngOnDestory(): void {}}
当界面属性值发生变化,亦或者是子组件中的值、服务中的属性值发生变化,其都会触发 ngDoCheck()、ngAfterContentChecked()、ngAfterViewChecked()
,所以我们只需要在这几个方法中去进行使用服务中的属性即可。