异步管道向子组件发送“空"值 [英] async pipe sends 'null' value to the child component
问题描述
我想向子组件传递一个值.这个值是一个 Observable,所以我使用异步管道.
<child [test]="test$ | async"></child>
test$ 只是一个普通的可观察变量,它会在一段时间(3000 毫秒)后发出值,模拟对服务器的 API 请求.
this.test$=timer(3000).pipe(映射到(值"))
在子组件中,我只想检查 test
值
@Input() 测试:任何;构造函数(){console.log("child/test", this.test);//空值setTimeout(()=>console.log("child/test (timeout)", this.test),4000)//值如果(这个.测试){//维护并检查`this.test`//这段代码不会运行,因为此时`this.test`为空.//我们不知道`this.test` 会有值的确切时间//这导致`this.test`是错误的this.checked=true}}
{{test}}
我不想将测试类型更改为 Observable
并订阅它.我想直接接收最终值.而且我根本不想修改编辑组件.
使用ChangeDetectorRef
手动触发变更检测器不是
@Input() test$:Observable构造函数(){this.test$.subscribe(v=>this.test=v)}
我还制作了这个 stackblitz 来检查在所有组件的钩子之间变化的值.
app.component.html
<child [test]="test"></child></ng-容器><ng-template #defaultTmpl>默认模板<ng-template>
更多详情请看:https://ultimatecourses.com/blog/angular-ngif-async-pipe
I want to pass a value to the child component. this value is an Observable, so I use async pipe.
<child [test]="test$ | async"></child>
test$ is just a normal observable variable, that emits values after a period of time (3000 ms), simulating an API request to the server.
this.test$=timer(3000).pipe(
mapTo("value")
)
in child component, I just want to check 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>
I don't want to change the type of test to be Observable
and subscribe to it.
I want to receive the final value directly.
and I don't want to modify the edit component at all.
using ChangeDetectorRef
to manually trigger the change detector is not
@Input() test$:Observable
constructor(){
this.test$.subscribe(v=>this.test=v)
}
I also made this stackblitz to check the value changing among all the compoonent's hooks.
app.component.html
<ng-container *ngIf=(test$ | async) as test; else defaultTmpl>
<child [test]="test"></child>
</ng-container>
<ng-template #defaultTmpl>Default Template<ng-template>
For more details please take a look: https://ultimatecourses.com/blog/angular-ngif-async-pipe
这篇关于异步管道向子组件发送“空"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!