Angular 中,在组件中有两个生命周期函数:ngOnInit 和 constructor。constructor 是 TypeScript 中类的构造函数,而 ngOnInit 则是 Angular 组件的初始化方法。因为它们都按照不同的时间发生,所以应该确保在适当的时候放置适当的代码。
constructor 中通常会放置组件所需的 DI(Dependency Injection)注入器、服务、配置参数等等。但是,你应该避免在 constructor 中进行更多的工作,因为这会增加代码启动时间并导致代码效能下降。
ngOnInit 中是初始化组件所需的最佳位置,你可以在其中放置代码,例如获取数据或很多其他初始化任务。此外,你还可以确保在 ngOnInit 中访问生命周期函数中的 ViewChild、Input 和 Output 属性。
下面是一个包含示例代码的例子:
@Component({
selector: 'app-example',
template: {{ message }}
})
export class ExampleComponent implements OnInit {
message: string;
constructor(private exampleService: ExampleService) { // DI 注入器在此放置 }
ngOnInit() { // 组件的初始化代码在此放置 this.exampleService.getMessage() .subscribe(response => this.message = response); } }