繁体   English   中英

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

[英]Angular2 @Input from async pipe - availability in ngOnInit

在一个博客上我读过:

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

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

<myComponent [myInput]="myObservableVariable | async">
 ...
</myComponent>

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

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

简短的答案是否定的,组件实例化不会被延迟, 如果在第一个更改检测周期之前尚未解析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>

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

async管道有一个方法transform ,在每个更改检测周期都会调用它。 此方法负责返回将传递给子组件的observable的当前已解析值。 如果在第一个更改检测周期之前尚未解析observable,则子组件将在onInit null

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

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

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);
}

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

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

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

我知道这个问题已得到解答,但也提供了官方参考资料,因为它在文档中很好地介绍了它: https//angular.io/guide/reactive-forms#when-to-set-form-model-values-ngonchanges

更改检测和生命周期挂钩从Observable值解析独立发生(因此是异步),因此您无法保证在onInit时您将拥有数据。 这正是onChanges的用途。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM