使用带有RxJS的Angular 5可以看到带有过滤器的数组

kum*_*umo 1 rxjs typescript angular angular5

我正在创建一个简单的论坛。

我想过滤帖子。我在RxJS中使用.pipe和.filter遇到了一些麻烦。

我试图:

  • 从中检索in-memory-api帖子列表api/posts,当与http.get一起使用时,它返回一个Observable<Post[]>
  • 重复遍历Post中的Observable<Post[]>每个帖子并对其进行过滤,以便仅选择ID为1(每个ID的帖子1)的每个帖子。
  • 将任何错误或功能成功登录到控制台

filter不选择在每个单独的片Post[]阵列,而是选择Post[]本身。

我的代码:

getPosts(): Observable<Post[]> {

  // Sets the url to the service's postsUrl
  const url = this.postsUrl;

  // The http.get returns an Observable<Post[]>
  return this.http.get<Post[]>(url)
    .pipe(
      filter(
        post: Post => post.id == 1
      ),
      // Log posts were fetched
      tap(posts => console.log('Posts fetched.')),
      // Error handling
      catchError(this.handleError('getPosts', []))
    );
 }
Run Code Online (Sandbox Code Playgroud)

我的错误:

Property 'id' does not exist on type 'Post[]'
Run Code Online (Sandbox Code Playgroud)

在我看过的所有示例中,过滤器都没有此问题。我认为它应该遍历Post[]数组中的所有值,因此我可以将其作为Post类型进行访问。


答案后编辑

根据接受的答案,我的最终代码如下所示:

posts.service.ts

getPosts(): Observable<Post[]> {

  const url = this.postsUrl;

  // Return the observable with array of Posts
  return this.http.get<Post[]>(url)
    .pipe(
      // Log posts were fetched
      tap(posts => console.log('Posts fetched.')),
      // Error handling
      catchError(this.handleError('getPosts', []))
    );

}
Run Code Online (Sandbox Code Playgroud)

posts.component.ts

private getPosts(): void {
  this.service.getPosts()
    // Map posts to a filtered version
    .map(
      posts => posts.filter(
        post => post.from_board_id == this.from_board_id
      )
    )
    // Subscribe it
    .subscribe(
      posts => this.posts = posts
    )
  ;
}
Run Code Online (Sandbox Code Playgroud)

Lea*_*ima 5

可观察值是价值流。您对RXJS表示您将收到的流Post[],换句话说,是Array<Post>

如果要过滤数组,可以执行以下操作:

 return this.http.get<Post[]>(url).map(posts => posts.filter(post => post.id === 1))
Run Code Online (Sandbox Code Playgroud)