obs观测值
In the last year or so, I’ve been fully embracing reactive programming in my Angular apps. That means goodbye subscribe
and hello async
pipe! It’s been great, but there have been a couple times where the async
pipe, in conjunction with the *ngIf
structural directive, have not worked as I needed them to. The issue arises when the emitted value from the observable is falsy. When the emitted value is falsy, the *ngIf
doesn’t output the content on the screen. I understand why that happens, but many times the falsy value is a valid result and should be displayed. In this post, we’ll cover an easy way to still use the async
pipe and *ngIf
while still outputting falsy values.
在过去一年左右的时间里,我一直在Angular应用程序中全面采用React式编程。 这意味着再见subscribe
和您好async
管道! 很棒,但是有好几次async
管道与*ngIf
结构化指令一起使用时,并没有按我的要求工作。 当可观察到的发射值是虚假的时,就会出现问题。 当发出的值错误时, *ngIf
不会在屏幕上输出内容。 我知道为什么会发生这种情况,但是很多时候伪造的值都是有效的结果,应该显示出来。 在本文中,我们将介绍在仍然输出错误值的同时仍使用async
管道和*ngIf
的简单方法。
问题说明 (The Issue Explained)
Recently, I was working on an application at work where we needed to output the emitted value of an observable. The value was a number with zero being a valid result. We also wanted to display a loading spinner while waiting on data from the API. We did that with the *ngIf
structural directive and the else
option that goes along with it. Here’s a brief sample of what that looked like:
最近,我正在工作的应用程序上需要输出可观察到的发射值的应用程序。 该值是一个数字,其中零为有效结果。 我们还想在等待来自API的数据时显示加载微调框。 我们使用*ngIf
结构指令和它附带的else
选项来完成此操作。 这是一个简短的样例:
&