【问题标题】:How to set two Async Pipe functions in Angular 7? [duplicate]如何在 Angular 7 中设置两个异步管道函数? [复制]
【发布时间】:2020-04-27 09:15:24
【问题描述】:

我有 2 个检查特定条件的函数,我希望它们都为真。 在这种情况下,您将如何使用 *ngIf?目前,如果我设置其中一个它可以工作,但我需要它们两个。

HTML

<p *ngIf="(isFree$ | async) && (order$ | async)">Free Plan</p>

TS

public order(data) {
    const order = data.externalOrderId;
    if (order.substring(0, 4) === 'asdad') {
      return true;
    } else {
      return false;
    }
  }


 public isFree$ = this.planType$.pipe(
    map((data) => {
      return (data.plan === 'Free');
    }
));

【问题讨论】:

  • 不,我看到了这个;所以我需要条件为真......我如何在 ngIf 中使用 and
  • 无法理解!
  • 合并 observables 并使用 map 运算符将它们编组为布尔值。
  • @TheHeadRush 怎么样?
  • 这真的取决于你正在组合的可观察对象。您可能应该查看learnrxjs.io/operators/combination,看看哪个运算符最适合您的用例。

标签: javascript html angular pipe


【解决方案1】:
  • 创建一个具有 (2) 个输入的新哑组件:[isFree]、[order]

  • 在您的新组件中,如果两个输入都可用,则使用 *ngIf 语句显示 &lt;p&gt;

【讨论】:

  • 什么意思?
  • 父组件应该包含可观察对象并将它们作为inputs 提供给拥有p 的哑组件。仅在定义了两个输入时才显示 p 元素
【解决方案2】:

你可以使用 rxjs forkJoin

它会等到两个 observables 流都返回响应。它返回单个可观察的响应数组,您可以订阅或使用 async 管道来解决

HTML

<p *ngIf="resp$ | async">Free Plan</p>

TS

public isFree$ = this.planType$.pipe(
    map((data) => {
      return (data.plan === 'Free');
    }
));

public isOrder$ = of({resp:[]}) // stream 2

public resp$ = forkJoin(this.isFree$, this.isOrder$)

Fork join example with ngIf and async

【讨论】:

  • 好像forkjoin已经被弃用了?
  • @user12684453 它在哪个版本中被弃用了?我不这么认为。
  • 它已在 rxjs 中被弃用
  • 不,不是。我已经为您提供了教程示例的链接。这是官方文档的链接rxjs.dev/api/index/function/forkJoin
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多