【问题标题】:How to handle `ngIf` with async pipe values?如何使用异步管道值处理`ngIf`?
【发布时间】:2019-11-25 05:45:23
【问题描述】:

我正在尝试使用async 管道来实现ngIf。但不起作用。有人帮我吗?

这是我的html:

<div class="response-container">
    xx {{response | async | json }}
    <div class="failed-error" *ngIf="(response.responseFail | async )">
        {{response.message}}
    </div>
    <div class="success-msg" *ngIf="(response.responseSucc | async) === 'true' ">
        {{response.message}}
    </div>
</div>

在上面的xx {{response | async | json }} 中打印为:

xx { "responseFail": false, "responseSucc": true, "message": "success" }

但为什么这不适用于*ngIf 条件?

【问题讨论】:

  • 控制台中是否显示任何错误?
  • 您需要将绑定值绑定到异步,因此在评估该值时它将返回真或假,例如。 response | async as _response 但我会将其添加到响应容器中,然后在您的失败错误中我会像这样检查*ngIf="_response.responseFail 而不是您 asnyc。
  • @JohnKane 是的,没有错误。

标签: angular angular-directive angular8


【解决方案1】:

response 是一个数据源,而 response.responseFail 不是一个。试试这个:

*ngIf="(response | async )?.responseFail"

*ngIf="(response | async)?.responseSucc  === 'true' "

【讨论】:

    【解决方案2】:

    你必须在异步管道之后访问对象 =>

    *ngIf="(response | async )?.responseFail"
    

    ex =>

    https://stackblitz.com/edit/angular-tvmqzm

    编辑:ethan 最先到达这里。

    【讨论】:

      【解决方案3】:

      除了前面的答案,你不应该在同一个 observable 上多次使用异步管道。

      最好这样做: (最好用 $ 命名 observabkes)

      <div *ngIf="response$ | async as response" class="response-container">
          xx {{response | json }}
          <div class="failed-error" *ngIf="response.responseFail">
              {{response.message}}
          </div>
          <div class="success-msg" *ngIf="response.responseSucc">
              {{response.message}}
          </div>
      </div>
      

      由于这些 div 仅在类上有所不同,您应该考虑使用 ng-class

      【讨论】:

        猜你喜欢
        • 2022-08-11
        • 2018-10-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2020-08-24
        • 2016-06-24
        • 2021-01-18
        • 2023-03-16
        相关资源
        最近更新 更多