当在 Angular 中使用异步管道时,不会立即触发事件(http 请求或任何有延迟的可观察值),得到的第一个值是null
为什么会发生这种情况?如何避免这种情况?
<hello [data]="delayedData$|async"> </hello>
第一个改变:
SimpleChange {
currentValue: null
firstChange: true
previousValue: undefined
}
第二个变化:
SimpleChange {
currentValue: 'some real data'
firstChange: false
previousValue: null
}
stackblitz 上的示例:https://stackblitz.com/edit/http-async-pipe-crxm32 https://stackblitz.com/edit/http-async-pipe-crxm32
这是预期的行为。为了避免它,你可以使用*ngIf
指示:
<hello *ngIf="delayedData$|async as delayedData" [data]="delayedData"> </hello>
这只会渲染hello
仅当组件delayedData$
已发出一个值。
ngIf 上的 Angular 文档 https://angular.io/api/common/NgIf
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)