如何使用异步管道值处理`ngIf`?

时间:2019-07-16 13:13:21

标签: angular angular-directive angular8

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

这是我的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条件?

3 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:2)

您必须在异步管道=>

之后访问对象
*ngIf="(response | async )?.responseFail"

ex =>

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

编辑:ethan首先来到这里。

答案 2 :(得分:1)

除了先前的答案外,您不应多次在同一可观察对象上使用异步管道。

最好这样做: (用$命名观察标记是最佳做法)

<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

相关问题