angular - 在循环 asyc 内请求数据时启动无限请求
问题描述
使用带有打字稿的 Angular 我有以下组件类:
@Injectable()
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html'
})
export class MyComponent implements OnInit{
public myList : any[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get("url").subscribe(result => {
this.myList= result;
}, error => console.log(error));
}
getSubitem(id){
return this.http.get("url/"+id).subscribe(result => {
return result;
}, error => console.error(error));
}
}
并遵循 html 片段:
<table>
<thead>
<tr>
<th>ID</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of myList">
<td>{{item.id}}</td>
<td>{{(getSubitem(item.id) | async)}}</td>
</tr>
</tbody>
现在,启动应用程序并转到该视图,myList
即可正确加载和显示。但是getSubitem
会无限次触发,以使浏览器崩溃。
如何确保getSubitem
每个 MyList-Item 只调用一次并显示正确的信息?
解决方案
问题在于它不断更新视图,一遍又一遍地调用 getsubitem() 函数。
这可能是异步加载项目的更好方法:
零件:
@Injectable()
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html'
})
export class MyComponent implements OnInit{
public myList : any[] = [];
public subitems: Object = {};
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get("url").subscribe(result => {
this.myList= result;
for(let item of this.myList){
this.getSubitem(item.id);
}
}, error => console.log(error));
}
getSubitem(id){
return this.http.get("url/"+id).subscribe(result => {
this.subitems[id] = result;
}, error => console.error(error));
}
}
HTML:
<table>
<thead>
<tr>
<th>ID</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of myList">
<td>{{item.id}}</td>
<ng-container *ngFor="let subitem of subitems[item.id]">
<td>{{subitem}}</td>
</ng-container>
</tr>
</tbody>
让我知道这是否适合您。
推荐阅读
- java - 检查 Google 计算 VM 实例状态
- node.js - 如何从函数返回数据并在nodejs中使用
- python - 使用 OpenModelica 的 OMPython 运行代码时,Jupyter 抛出错误“OMC 服务器已关闭..”
- python - 与盒子碰撞问题如何解决?游戏
- unity3d - 为什么 Mesh Collider 不完全遵循 3D 对象的网格?
- spring-boot - spring-boot-starter-jetty 的默认响应超时是多少
- javascript - TypeScript 无法编译 - 发现错误附加的项目
- javascript - 未捕获(承诺)错误:arrayToDataTable 的数据不是使用 https://www.google.com/jsapi 可视化数据的数组
- c# - 在 Mac 和 Winforms 上运行 Mono C# 项目
- excel - VBA 论坛超过 255 个字符的公式数组。替换为 vba 单元格引用