迭代由 observable 提供的对象数组并调用 http 请求 foreach object.id?

J.D*_*Doe 1 observable typescript angular

通过组件ngOnInit方法中 Angular 中的路由,我通过 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'];
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

它返回这个:

   "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",
      .
      .
      .
    }, ...
   ]
Run Code Online (Sandbox Code Playgroud)

它返回的是没有演员表的电影,因此我需要通过为第一个请求返回的每部电影调用另一个 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);
      }
    }); 
  }
Run Code Online (Sandbox Code Playgroud)

按类型获取电影,当结果到达时,迭代数组movies[]并调用方法以按电影 id 获取演员表,并将演员表添加到电影casts: string []属性中。并返回this.movies: Movies[],其中现在也包含强制转换。

小智 5

当你在 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
      });
  })
}
Run Code Online (Sandbox Code Playgroud)

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

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