简体   繁体   English

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

[英]How to handle `ngIf` with async pipe values?

I am trying to implement the ngIf with using async pipe. 我正在尝试使用async管道实现ngIf but not works. 但不行。 any one help me here? 有人帮我吗?

here is my html: 这是我的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>

in the above xx {{response | async | json }} 在上面的xx {{response | async | json }} xx {{response | async | json }} xx {{response | async | json }} it prints as: xx {{response | async | json }}它打印为:

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

But why this is not works with *ngIf condition? 但为什么这不适用于*ngIf条件?

The response is a data source while response.responseFail is not one. response是数据源,而response.responseFail不是一个。 Try this: 尝试这个:

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

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

you have to access the object after the async pipe => 你必须在异步管道=>之后访问该对象

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

ex => ex =>

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

edit : ethan got here first. 编辑:ethan先来到这里。

Besides the previous answers, you shouldn't use the async pipe on the same observable several times. 除了以前的答案,你不应该在同一个observable上多次使用异步管道。

Better do this: (naming observabkes with $ is best practice) 更好地做到这一点:(用$命名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>

And since those div's only differ in class you should consider using ng-class 由于这些div只在课堂上有所不同,你应该考虑使用ng-class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM