angular - 遍历由可观察对象提供的对象数组并调用 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[]
现在也包含演员表。
解决方案
当你在 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 中的请求失败,则整个执行都会失败,因此您应该针对每个请求专门处理错误。
推荐阅读
- laravel - Laravel - 用户有很多画廊 - 画廊有很多图片 -> 如何在 DB 中插入
- javascript - 如何使用 Javascript 或 JQuery 安全地将输入数据属性附加到按钮
- c# - C#/Razor 如果引用者等于或包含
- angular - 通过@ViewChild 获取异步数据
- android - Android Studio:配置离线构建依赖项
- azure - 在 Azure DevOps 上的 Build.ArtifactStagingDirectory 中创建一个文件
- kubernetes - Kubernetes 主节点标签
- email - 是否有任何服务或邮政服务可以帮助我更改电子邮件编码和转发 ir?
- javascript - Momentjs 无法区分两个日期
- python - 如何解决 KeyError:“[Index(['t1'], dtype='object')] 均不在 [columns] 中”