Angular中如何在subscribe外部返回异步请求获取的有效数组
解决方案
问题核心是异步请求的结果无法同步返回,直接返回数组时请求还没完成,所以拿到的是空数组。可以通过以下方式改造:
1. 改造TypeScript方法,返回Observable
把winServiceInfo改成返回Observable,利用RxJS的map操作符处理异步返回的数据:
winServiceInfo(j: number): Observable<any[]> { this.winServiceURL = JSON.parse(this.WinService[j].windowsServicesInfo)["Stactuscheck"]; return this.service.getWinServicesInfo(this.winServiceURL) .pipe( catchError(this.handleError), map(data => { this.setSubscribeData(data); return this.dataArrs; }), shareReplay(1) // 可选:缓存请求结果,避免重复调用时重复发起请求 ); }
2. 模板中使用async管道订阅Observable
Angular的async管道会自动处理Observable的订阅和取消订阅,等异步数据返回后再渲染列表:
<div class="row" *ngFor="let otc of this.jsonData;index as j"> <div> <table class="table table-striped table-fixed"> <tr *ngFor="let opc of winServiceInfo(j) | async;index as i"> <!-- 这里填充你的表格内容 --> </tr> </table> </div> </div>
补充说明
- 确保
handleError方法返回一个合法的Observable(比如return of([])),避免请求出错时模板报错; shareReplay(1)用于缓存请求结果,如果同一个j值多次调用winServiceInfo,只会发起一次请求,后续直接复用缓存数据,优化性能。
内容的提问来源于stack exchange,提问作者Rock
相关产品推荐
相关产品推荐

