我想将一个值传递给子组件。这个值是一个 Observable,所以我使用异步管道。
<child [test]="test$ | async"></child>
test$ 只是一个普通的可观察变量,它会在一段时间(3000 毫秒)后发出值,模拟对服务器的 API 请求。
this.test$=timer(3000).pipe(
mapTo("value")
)
在子组件中,我只想检查
test
值(value)@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)
}
我也做了这个stackblitz检查所有组件钩子(Hook)之间的值变化。
最佳答案
async
管道将返回 null
当 Observable
没有发出任何值时然而。所以,test
的值在子组件中是:
undefined
在构造函数中,因为 @Input()
在此状态下未分配变量 null
之后(例如,第一个 onChanges
钩子(Hook)或 onInit
钩子(Hook)`)当 Observable value
当 Observable 发出新值 现在,您应该仅在
test
时创建子组件。变量不是 null
与 *ngIf
, 或正确处理子组件的状态为空 test
(例如,当 test
为空时添加进度条)。这个选择由你。
关于angular - 异步管道向子组件发送 'null' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61681239/