来自异步管道的Angular2 @Input - ngOnInit中的可用性

cha*_*_pl 10 angular

在一个博客上我读过:

ngOnInit生命周期钩子可以保证您的绑定随时可用.

使用异步管道传递的参数也是如此吗?例如:

<myComponent [myInput]="myObservableVariable | async">
 ...
</myComponent>
Run Code Online (Sandbox Code Playgroud)

在启动ngOnInit之前,组件是否会等待变量被解析?

这意味着有时,当数据需要一段时间才能解决时,组件加载可能需要很长时间.

Max*_*kyi 11

简短的答案是否定的,组件实例化不会被延迟,如果在第一个更改检测周期之前尚未解析observable,不会获得解析值onInit .

比较以下内容:

  // the value will be available in onInit
  obs = Observable.from([33]);

  // the value will not be available in onInit (you'll get null)
  obs = new Observable(observer => {
    setTimeout(() => {
      observer.next(33);
    }, 1000);

    setTimeout(() => {
      observer.complete();
    }, 3000);
  });


<child-component [inputproperty]="obs"><child-component>
Run Code Online (Sandbox Code Playgroud)

以下是使用async管道时引擎盖下发生的情况:

async管道有一个transform在每个变化检测周期都要调用的方法.此方法负责返回将传递给子组件的observable的当前已解析值.如果观察到的尚未在第一变更检测周期解决之前,你的孩子组件将获得nullonInit.

然后,在下一个摘要周期中,您的绑定将更新,transform并将返回已解析的值.有趣的是,可观察的分辨率可以触发变化检测周期.您可以在onChanges生命周期钩子中获取绑定的新值.

  • 这是对异步管道内部工作原理的非常好的洞察。这解释了很多,谢谢! (2认同)
  • @charlie_pl,欢迎您,您可能会发现关于更改检测的[这篇文章](https://hackernoon.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f)很有趣以及 (2认同)

jon*_*rpe 5

不,绑定可用并不意味着它们的值已经解决(并且它们可能会在以后更改).您可以通过一个简单的示例演示:

import { Component, Input, OnInit } from '@angular/core';

import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'sub-component',
  template: `<p>{{ myInput }}</p>`,
})
export class SubComponent implements OnInit {
  @Input() myInput: string;

  ngOnInit() {
    console.log('initialised with', this.myInput);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1>
    <sub-component [myInput]="content$ | async"></sub-component>
  `
})
export class AppComponent { 
  name = 'Angular'; 
  content$ = Observable.of('Hello world').delay(5000);
}
Run Code Online (Sandbox Code Playgroud)

https://plnkr.co/edit/jX7hOafuJtsWYhYrJx07?p=preview

在控制台中,您将看到initialised with null,然后五秒钟后,文本将出现在子组件中.

如果您想知道@Input数据何时发生变化,则需要实施OnChanges.