Angular中Observable订阅结果适配*ngFor数组格式问题
解决方案
你的问题出在订阅逻辑中逐个发送单个对象到Subject,导致每次订阅Subject时都会把plans重置为仅包含当前对象的数组,最终无法得到完整的列表数组。以下是两种修复方案:
方案1:直接赋值(无需Subject,适合单组件使用)
如果不需要跨组件共享数据,直接在getUserModuleInstalled的订阅中给plans赋值完整数组即可:
this.getUserModuleInstalled().subscribe((data: any[]) => { if (data) { // 过滤掉请求失败返回的null值 this.plans = data.filter(plan => plan !== null); console.log('Plans data:', this.plans); } else { this.plans = []; console.log('No data received'); } }, (error: any) => { this.plans = []; console.error('Error:', error); });
方案2:使用Subject共享完整数组(适合多组件订阅场景)
如果需要通过Subject共享数据,需修改Subject的类型为数组类型,并直接发送完整数组,而非单个对象:
// 先将Subject定义为数组类型 plansSubject = new Subject<ModulesSub[]>(); // 订阅getUserModuleInstalled并发送完整数组 this.getUserModuleInstalled().subscribe((data: any[]) => { if (data) { const validPlans = data.filter(plan => plan !== null); this.plansSubject.next(validPlans); console.log('New plans data:', validPlans); } else { this.plansSubject.next([]); console.log('No data received'); } }, (error: any) => { this.plansSubject.next([]); console.error('Error:', error); }); // 订阅Subject时直接接收完整数组 this.plansSubject.subscribe((plans: ModulesSub[]) => { this.plans = plans; console.log('Plans data:', this.plans); });
可选优化:提前过滤无效数据
在getUserModuleInstalled函数中加入filter(Boolean),提前过滤掉请求失败返回的null值,减少后续处理逻辑:
getUserModuleInstalled(): Observable<any[]> { const userId = this.user.id; return this._moduleService.getUserModule(userId).pipe( switchMap((response: any) => { return from(response.user_module || []).pipe( concatMap((userModule: any) => { const moduleId = userModule.module_id; console.log('User module Id response=> '+moduleId); return this._moduleService.getSubscriptionModule(moduleId).pipe( map(subModule => subModule.data.subscription_modules), catchError(error => { console.error(error); return of(null); }) ); }), filter(Boolean), // 过滤null值 toArray(), catchError(error => { console.error(error); return of([]); }) ); }) ); }
内容的提问来源于stack exchange,提问作者Alexander Quiroz
相关产品推荐
相关产品推荐

