Angular 在循环asyc中请求数据时启动无限请求
使用Angular with typescript,我有以下组件类:Angular 在循环asyc中请求数据时启动无限请求,angular,typescript,Angular,Typescript,使用Angular with typescript,我有以下组件类: @Injectable() @组成部分({ 选择器:“应用程序mycomponent”, templateUrl:“./mycomponent.component.html” }) 导出类MyComponent实现OnInit{ 公共myList:any[]=[]; 构造函数(私有http:HttpClient){} ngOnInit():void{ this.http.get(“url”).subscribe(结果=>{ t
@Injectable()
@组成部分({
选择器:“应用程序mycomponent”,
templateUrl:“./mycomponent.component.html”
})
导出类MyComponent实现OnInit{
公共myList:any[]=[];
构造函数(私有http:HttpClient){}
ngOnInit():void{
this.http.get(“url”).subscribe(结果=>{
this.myList=结果;
},error=>console.log(error));
}
getSubitem(id){
返回此.http.get(“url/”+id).subscribe(结果=>{
返回结果;
},error=>console.error(error));
}
}
在html代码片段之后:
身份证件
{{item.id}
{{(getSubitem(item.id)| async)}
现在,启动应用程序并转到该视图,myList
被正确加载和显示。但是getSubitem
被无限次触发,因此浏览器崩溃
如何确保对每个MyList项只调用一次
getSubitem
,并显示正确的信息?问题在于它不断更新视图,反复调用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:
身份证件
{{item.id}
{{子项}}
让我知道这是否适合您。问题在于它不断更新视图,反复调用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:
身份证件
{{item.id}
{{子项}}
让我知道这是否适用于您。预先将子项加载到不同的变量中,并在HTML中迭代这些子项<代码>公共结果:任意和subscribe
result=>this.result=result
预先将子项加载到不同的变量中,并在HTML中迭代这些子项<代码>公共结果:任意代码>和订阅result=>this.result=result