首页 > 解决方案 > 遍历由可观察对象提供的对象数组并调用 http 请求 foreach object.id?

问题描述

通过组件方法中的 Angular 路由,ngOnInit我通过 observable 获得了流派 id,在该 observable 中,我调用了一个带有发出 HTTP 请求的服务的方法。

  this.movies: Movie[];

  ngOnInit() {
    this.route.paramMap.subscribe(param => {
      let id = +param.get('id');

      this.movieService.getMoviesByGenres(id).subscribe( response => {
        this.movies = response['results'];
      });
    });
  }

它返回这个:

   "results": [
    {
      "vote_count": 664,
      "id": 287947,
      "video": false,
      "vote_average": 7.4,
      "title": "Shazam!",
      .
      .
      .
    },
    {
      "vote_count": 3623,
      "id": 299537,
      "video": false,
      "vote_average": 7.2,
      "title": "Captain Marvel",
      .
      .
      .
    }, ...
   ]

它返回的是没有演员表的电影,所以我需要通过为第一个请求返回的每个电影调用另一个 HTTP 请求来请求电影的演员表,并将演员表的第二个请求信息推送到movies[i].cast数组。

所以基本上我想要的,看起来像这样:

  ngOnInit() {
    this.route.paramMap.subscribe(param => {
      let id = +param.get('id');

      this.movieService.getMoviesByGenres(id).subscribe( response => {
        this.movies = response['results'];
      });

      //pesudo code
      foreach(this.movies as movie) {
             this.movies[current element].casts = 
                  this.movieService.getCastByMovieId(movie.id);
      }
    }); 
  }

按类型获取电影,当结果到达时,遍历movies[]数组并调用方法以通过电影 id 获取演员表并将演员表添加到电影casts: string []属性。并且 returnthis.movies: Movies[]现在也包含演员表。

标签: angulartypescriptobservable

解决方案


当你在 Angular 中工作时,你也可以利用 RxJS 的力量来做这件事,就像这样

public ngOnInit(): void {
  this.route.paramMap.subscribe(param => {
    let id = +param.get('id');

    this.movieService.getMoviesByGenres(id).pipe(
      map(response => response['results']),
      mergeMap((movies: any[]) => {
        return forkJoin(
          movies.map(movie => {
            return this.movieService.getCastByMovieId(movie.id)
              .pipe(
                map((res: any) => {
                  movie.cast = res;
                  return movie;
                })
              );
          })
        )
      }))
      .subscribe(movies => {
        // Your logic here
      });
  })
}

基本上你首先得到电影,然后通过一个 forkJoin 管道结果,它一起执行请求并保持顺序,将结果添加到 movie.cast 并在最后返回完整的数组。通过这种方式,您还可以知道执行何时完成。

请记住,如果 forkJoin 中的请求失败,则整个执行都会失败,因此您应该针对每个请求专门处理错误。


推荐阅读