Angular:试图使嵌套的可观察性发挥作用



在我的一生中,我无法理解嵌套的可观察性。我想我可能需要回到训练视频中,比现在更深入地了解。我理解所有的基本概念,但把它们放在一起很难。

目前,我正在努力让这个特定的应用程序发挥作用。我有一个工作示例,其中我调用了一个api,并返回了一个绑定到接口的数组。对于这个数组的每个成员,我需要使用接口中的值来查找另一个api。我将从第二个api收到一个值,我想将其存储在接口中。

我模拟了一个我在stackblitz上尝试做什么的例子。如有任何帮助,我们将不胜感激。

https://stackblitz.com/edit/call-http-request-in-angular-6-kyq1an?embed=1&file=src/app/app.component.ts

我希望它能对你有所帮助。

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { concatMap, switchMap, take, toArray, map } from 'rxjs/operators';
import { from } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 6';
constructor(private http: HttpClient) { }
public url = "https://jsonplaceholder.typicode.com/todos";
public httpData: IPostWithComments[];
ngOnInit() {
this.http.get(this.url)
.pipe(
// Reveiced an array of posts
// Use "from" emit each value one by one
switchMap((posts: IPost[]) => from(posts)),
// Take(10) to avoid too many requests
take(10),
// For each post, fetch comments associated
concatMap((post: IPost) => this.http.get(`${this.url}/${post.id}/comments`)
.pipe(
// Only take the first five comments
map((comments: IComment[]) => comments.splice(0, 5))
),
// Use result selector function to add comments in the post object
(post: IPost, comments: IComment[]) => {
const postWithComments: IPostWithComments = {...post, comments};
return postWithComments;
}
),
// Aggregate all the posts in an array
toArray()
)
.subscribe((postsWithComments: IPostWithComments[]) => {
console.log(postsWithComments);
this.httpData = postsWithComments;
})
}
}
interface Kafein {
name:string;
address:string;
}
interface IPost {
completed: boolean;
id: number;
title: string;
userId: number;
}
interface IPostWithComments extends IPost {
comments: IComment[]
}
interface IComment {
body: string;
email: string;
id: number;
name: string;
postId: number;
}

Stacklitz

最新更新