* ng如果具有多个异步管道变量

问题描述:

曾经尝试将两个可观察对象合并为一个*ngIf并在两个对象都发出时显示用户界面.

Been trying to combine two observables into one *ngIf and show the user interface when both have emitted.

接吻:

<div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
    <b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
</div>

来自:将两个异步订阅放入一个Angular * ngIf声明

这可以编译,但是在我的情况下,language$user$来自两个HTTP请求,并且似乎user$会抛出类似TypeError: _v.context.ngIf.user is undefined的运行时错误.

This works as far as it compiles however in my case language$ and user$ would be from two HTTP requests and it seems user$ throws runtime errors like TypeError: _v.context.ngIf.user is undefined.

基本上我真正想要的是(这不起作用):

Essentially what I really want is (this doesn't work):

<div *ngIf="language$ | async as language && user$ | async as user">
    <b>{{language}}</b> and <b>{{user}}</b>
</div>

是最佳解决方案:

  • 在组件内部订阅并写入变量
  • 使用withLatestFrom
  • 组合组件中的两个可观察对象
  • 添加空支票{{userLanguage?.user}}
  • Subscribe inside the component and write to variables
  • To combine the two observables inside the component with say withLatestFrom
  • Add null checks {{userLanguage?.user}}

此情况应使用嵌套的ngIf指令处理:

This condition should be handled with nested ngIf directives:

<ng-container *ngIf="language$ | async as language">
  <div *ngIf="user$ | async as user">
    <b>{{language}}</b> and <b>{{user}}</b>
  </div>
<ng-container>

缺点是HTTP请求将按顺序执行.

The downside is that HTTP requests will be performed in series.

为了同时执行它们并仍然具有languageuser变量,需要更多的嵌套:

In order to perform them concurrently and still have language and user variables, more nesting is required:

<ng-container *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
  <ng-container *ngIf="userLanguage.language as language">
    <ng-container *ngIf="userLanguage.user as user">
      <div><b>{{language}}</b> and <b>{{user}}</b></div>
    </ng-container>
  </ng-container>
</ng-container>

更有效的方法是将逻辑从模板移动到组件类,并创建一个可观察的对象,例如与withLatestFrom

More efficient way way to do this is to move logic from template to component class at this point and create a single observable, e.g. with withLatestFrom