我找到的关于这个话题的answers个人大约有7年的历史.总之,建议使用构造函数进行基本属性初始化、设置依赖项注入和不太复杂的任务.使用ngOnInit
进行更复杂的初始化,这些初始化涉及与服务的交互,如http请求、@input通信机制或其他特定Angular 的操作.
现在建议使用新的inject
函数来处理Angular DI,因为您可能会遇到es2022的问题.以下代码片段只是一个风格问题,还是有任何其他区别?
export class ExampleComponent {
private service = inject(Dependency);
}
export class ExampleComponent {
private service: Dependency;
constructor( ) {
this.service = inject(Dependency);
}
建议在构造函数中传递订户函数,还是应该在ngOnInit
个函数中定义该操作?
export class ExampleComponent {
private subscription: Subscription;
private service = inject(Dependency);
constructor( ) {
this.subscription = this.service.getAnObservable().subscribe(result => {
//do something on result
});
}