You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17中如何结合@defer与async pipe在模板声明变量

在Angular中用@defer实现异步变量赋值的正确方式

你之前尝试的@defer(when items$ | async; as items)写法确实不被Angular模板支持,因为@defer的when子句仅接受布尔判断表达式,不支持像@if那样的as赋值语法。

要实现类似@if的变量捕获效果,有两种常用的靠谱方式:

方式一:用@let提前捕获异步值(推荐)

在模板顶层用@let语法先把异步流的值存下来,之后在@defer的条件和块里直接使用这个变量,还能避免重复订阅:

@let items = items$ | async;

@defer(when items) {
  <!-- 这里直接用items变量就行 -->
  <div *ngFor="let item of items">{{ item.name }}</div>
} @loading {
  加载中...
}

方式二:@defer内部嵌套@if

如果不想在顶层声明变量,也可以在@defer的内容块里嵌套@if来捕获值,但要注意:如果items$是冷Observable,这种写法会触发两次订阅,建议给Observable加上shareReplay()操作符避免重复请求:

@defer(when items$ | async) {
  @if(items$ | async; as items) {
    <div *ngFor="let item of items">{{ item.name }}</div>
  }
} @loading {
  加载中...
}

内容的提问来源于stack exchange,提问作者imalphachild

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:17:35