[英]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.