角度:尝试使嵌套可观察到工作

时间:2020-04-24 20:01:50

标签: angular observable

在我的一生中,我无法绕过嵌套的可观测对象。我想我可能需要回到培训视频以比现在有了更深入的了解。我了解所有基本概念,但是将它们组合在一起非常困难。

目前,我正在尝试使此特定应用正常工作。我有一个工作示例,其中我要调用一个api并取回绑定到接口的数组。对于此数组的每个成员,我需要使用接口中的值来查找另一个api。我将从第二个要存储在界面中的api返回一个值。

我模拟了一个我想在Stackblitz上尝试做的事的例子。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:0)

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

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;
}

Stackblitz