Angular中AsyncPipe报InvalidPipeArgument: '10',数组长度显示NaN求助
解决AsyncPipe报错"InvalidPipeArgument: '10' for pipe 'AsyncPipe'"的问题
咱们先把问题拆明白:你在模板里用了async管道,但这个管道的作用是专门处理Observable或者Promise类型的数据,帮你自动订阅和销毁订阅。但你看你的TS代码,cfNotificationsLength明明被你赋值成了一个普通数字(x.Notifications.length),可你却给它声明成了Observable<number>类型,这就导致async管道拿到一个普通数字后懵了,直接抛出错误,页面自然显示NaN。
给你两个解决方案,按需选择:
方案一:直接移除AsyncPipe(最适合当前场景)
既然cfNotificationsLength是请求完成后同步得到的普通数字,完全不需要用async管道。修改步骤如下:
- 调整TS里的变量类型:
// 把Observable<number>改成普通number类型 public cfNotificationsLength: number; public cfNotifications: any; ngOnInit() { console.log("HeaderBarComponent loaded successfuly!"); this.referenceDataService.fetchNotifications(token) .subscribe((x: any) => { this.cfNotifications = x.Notifications; // 直接赋值数字 this.cfNotificationsLength = x.Notifications.length; console.log("cfNotifications", this.cfNotifications); console.log("cfNotificationsLength", this.cfNotificationsLength); }, (err: any) => console.log("error", err) ); }
- 修改模板代码,去掉
async管道:
<a href="#" class="dropdown-toggle dk" data-toggle="dropdown"> <i class="fa fa-bell"></i> <span class="badge badge-sm up bg-danger m-l-n-sm count" id="notcountbadge">{{cfNotificationsLength}}</span> </a>
方案二:用BehaviorSubject保留AsyncPipe(适合未来动态更新场景)
如果之后你需要动态更新通知数量(比如新增通知后自动刷新数字),可以把cfNotificationsLength改成BehaviorSubject(属于Observable的一种),这样就能继续用async管道了:
- 修改TS代码:
import { BehaviorSubject } from 'rxjs'; // 用$后缀区分Observable是Angular开发的惯例 public cfNotificationsLength$ = new BehaviorSubject<number>(0); public cfNotifications: any; ngOnInit() { console.log("HeaderBarComponent loaded successfuly!"); this.referenceDataService.fetchNotifications(token) .subscribe((x: any) => { this.cfNotifications = x.Notifications; const newLength = x.Notifications.length; // 发送新的长度值到Subject里 this.cfNotificationsLength$.next(newLength); console.log("cfNotifications", this.cfNotifications); console.log("cfNotificationsLength", newLength); }, (err: any) => console.log("error", err) ); }
- 调整模板代码:
<a href="#" class="dropdown-toggle dk" data-toggle="dropdown"> <i class="fa fa-bell"></i> <span class="badge badge-sm up bg-danger m-l-n-sm count" id="notcountbadge">{{cfNotificationsLength$ | async}}</span> </a>
推荐你先用方案一,因为当前场景下完全没必要引入Observable,简单直接就能解决问题。
内容的提问来源于stack exchange,提问作者Giannis
相关产品推荐
相关产品推荐

