首页 > 解决方案 > 在循环 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 只调用一次并显示正确的信息?

标签: angulartypescript

解决方案


问题在于它不断更新视图,一遍又一遍地调用 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>

让我知道这是否适合您。


推荐阅读