异步管道向子组件发送“空”值

Sh *_*eeb 4 observable rxjs angular-pipe angular async-pipe

我想将一个值传递给子组件。这个值是一个 Observable,所以我使用异步管道。

<child [test]="test$ | async"></child>
Run Code Online (Sandbox Code Playgroud)

test$ 只是一个普通的可观察变量,它在一段时间(3000 毫秒)后发出值,模拟对服务器的 API 请求。

this.test$=timer(3000).pipe(
      mapTo("value")      
 )
Run Code Online (Sandbox Code Playgroud)

在子组件中,我只想检查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 
     }
  }

Run Code Online (Sandbox Code Playgroud)
<div *ngIf="checked">{{test}}</div>
Run Code Online (Sandbox Code Playgroud)

我不想更改测试类型Observable并订阅它。我想直接接收最终值。我根本不想修改编辑组件。

使用ChangeDetectorRef手动触发变化检测器是不

@Input() test$:Observable

constructor(){
  this.test$.subscribe(v=>this.test=v)
}
Run Code Online (Sandbox Code Playgroud)

我还做了这个stackblitz来检查所有组件的钩子之间的值变化。

rob*_*b2d 20

更简单的解决方案:

(test$ | async) || defaultTestValue
Run Code Online (Sandbox Code Playgroud)


小智 7

应用程序组件.html

<ng-container *ngIf=(test$ | async) as test; else defaultTmpl>
    <child [test]="test"></child>
</ng-container>
<ng-template #defaultTmpl>Default Template<ng-template>
Run Code Online (Sandbox Code Playgroud)

更多详情请查看:https : //ultimatecourses.com/blog/angular-ngif-async-pipe


HTN*_*HTN 6

asyncnullObservable尚未发出任何值时,管道将返回。因此,test子组件中的值是:

  • undefined在构造函数中,因为@Input()在此状态下未分配变量
  • null之后(例如第一个onChanges钩子或钩子onInit`)当 Observable 没有发出任何值时
  • value 当 Observable 发出新值时

现在,你应该可以创建子组件,只有当test变量不null*ngIf,或正确处理可空子组件的状态test(例如,当添加一个进度条test为空)。这个选择由你。


Kam*_*Lar 3

您可以在模板中创建变量,如下所示:

test$ | async; let test;
Run Code Online (Sandbox Code Playgroud)

然后你可以检查:

*ngIf='test'

如果这是真的那么你可以渲染你的子组件。