angular - 异步管道向子组件发送 'null' 值

标签 angular rxjs observable angular-pipe async-pipe

我想将一个值传递给子组件。这个值是一个 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管道将返回 nullObservable 没有发出任何值时然而。所以,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/

    相关文章:

    创建共享模块后 angular-cli 测试失败

    angular - 使用另一个 InjectionToken 提供 InjectionToken

    rxjs - 需要帮助将 rxjs forkjoin 调用转换为异步调用(在 ngrx @Effect 内)

    javascript - RxJS 重试整个链

    c# - 处理先前的可观察 selectmany rx

    json - Table Angular 2 (ng2-smart-table) - 从 JSON 获取所有数据(对于 json 的每个级别)

    Angular 2+ 错误 : Cannot find name 'gapi'

    javascript - 使用 RxJS 一次限制请求数

    javascript - 如何在 Angular http 拦截器中以异步方式缓存 http 请求?

    javascript - 订阅 onComplete 永远不会用 flatMap 完成