这个值是一个Observable,所以我使用async管道。
<child [test]="test$ | async"></child>
test$只是一个普通的observable变量,它在一段时间后(3000毫秒)发出值,模拟向服务器发出API请求。
this.test$=timer(3000).pipe(
mapTo("value")
)
在子组件中,我只想检查 test
价值
@Input() test: any;
constructor(){
console.log("child/test", this.test); //null
setTimeout(()=>console.log("child/test (timeout)", this.test),4000) //value
if(this.test){
//maintain and check `this.test`
//this code will not run, because at this point `this.test` is null.
//we don't know the exact time that `this.test` will have a value
//this causes that `this.test` is wrong
this.checked=true
}
}
<div *ngIf="checked">{{test}}</div>
我不想把测试的类型改成了。Observable
我想直接接收最终值,而且我根本不想修改编辑组件。
使用 ChangeDetectorRef
手动触发变化检测器是不可能的。
@Input() test$:Observable
constructor(){
this.test$.subscribe(v=>this.test=v)
}
我还做了这个 爆料 来检查所有组件的钩子中的值变化。
<ng-container *ngIf=(test$ | async) as test; else defaultTmpl>
<child [test]="test"></child>
</ng-container>
<ng-template #defaultTmpl>Default Template<ng-template>
async
管子会回来 null
当 Observable
还。所以,价值的 test
在子组件中是。
undefined
因为在构造函数中 @Input()
变量在此状态下不被分配null
之后 onChanges
钩 onInit
钩子`),当Observable没有发出任何值时。value
当Observable发出新值时现在,你应该或者只在以下情况下创建子组件 test
变量不 null
与 *ngIf
或正确处理子组件的状态,用nullable test
(例如:当你在使用时,增加一个进度条。test
是空的)。) 选择权在你手里。
你可以像这样在你的模板中创建变量。
test$ | async; let test;
然后你就可以检查:
*ngIf='test'
如果它为真,你就可以渲染你的子组件。