我找到的关于这个话题的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
      });
    }

推荐答案

在旧的类型脚本中,属性的初始化在幕后移到构造函数代码的开头.

在ES2022中,属性的初始化是在构造函数中完成的,而不是在构造函数中.

所以你的例子没有区别,甚至

export class ExampleComponent {
  private service = inject(Dependency);
  private widget = this.service.getWidget();
}

export class ExampleComponent {
  private service: Dependency;
  private widget;

  constructor( ) { 
    this.service = inject(Dependency);
    this.widget = this.service.getWidget();
  }
}

是面向future 的,但

export class ExampleComponent {
  private widget = this.service.getWidget();

  constructor(private service: Dependency) {}
}

将来可能不会工作,但它今天可以工作,因为TypeScrip当前初始化widget-inside构造函数.

As a rule, I set up observables in the constructor, but observers in ngOnInit. The way I think of it, observables are just plumbing. Until subscribed to, nothing is flowing. In contrast, before you subscribe or otherwise add an observer your component must be set up 和 ready to go! This helps avoid bugs where the code is waiting for a value that was streamed/emitted before all the plumbing was in place.

Angular相关问答推荐

如何在自定义验证器中获取所有表单控件(字段组动态创建)

如何动态呈现组件并以Angular 访问它们的方法?

如何使用ANGLING HTTP.POST并将类型更改为键入的回复?

无法创建新的 Ionic 项目

在指令中获取宿主组件的templateRef

执行ng generate environments时出错时需要合集和原理图

没有调用订阅的原因是什么?

根据变量值更改按钮样式

如何以编程方式关闭 ng-bootstrap 模式?

无法卸载 angular-cli

如何在不刷新整页的情况下更新组件

Angular 4 - 在下拉列表中 Select 默认值 [Reactive Forms]

如何在Angular 4中为数字管道指定语言环境千位分隔符

Angular 2 - 全局 CSS 文件

如何在 Angular 2 的同一个组件中使用多个 ng-content?

Angular 2:组件交互,可选输入参数

如何在 Angular 2 中链接 HTTP 调用?

Firebase 查询子项的子项是否包含值

如何在 Angular 2 中跟踪路由?

Angular2/4 中的ng-reflect-*属性有什么作用?