使用带有RxJS的Angular 5可以看到带有过滤器的数组 [英] Observable of array with filter using Angular 5 with RxJS

查看:61
本文介绍了使用带有RxJS的Angular 5可以看到带有过滤器的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a simple forum.

我正在寻找帖子.我在RxJS中使用.pipe和.filter遇到了一些麻烦.

I'm looking to filter the posts. I have some trouble with .pipe and .filter in RxJS.

我正在尝试:

  • api/posts检索内存中api帖子列表,当与http.get一起使用时,它返回Observable<Post[]>
  • 遍历Observable<Post[]>中的每个Post并对其进行过滤,以便仅选择ID为1的每个帖子(只有一个ID为1的帖子存在).
  • 将任何错误或功能成功登录到控制台
  • Retrieve the list of in-memory-api posts from api/posts, which when used with http.get it returns an Observable<Post[]>
  • Iterate through each Post in the Observable<Post[]> and filter it so it only selects, says, each post with an id of 1 (only one post with id 1 exists).
  • Log to the console any errors or if the function had success

filter不会选择Post[]数组中的每个单独的片段,而是选择Post[]本身.

The filter does not select each individual piece in the Post[] array, but instead selects Post[] itself.

我的代码:

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', []))
    );
 }

我的错误:

Property 'id' does not exist on type 'Post[]'

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

In all examples I've looked at, the filter does not have this issue. I'm thinking it should iterate through all values in the Post[], array, so I can access it as a Post type.

答案后编辑

基于接受的答案,我的最终代码如下:

My final code, based on the accepted answer, looks like this:

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', []))
    );

}

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

推荐答案

可观察值是值的流.您对RXJS表示您将收到Post[]流,即Array<Post>.

Observables are stream of values. You are saying to RXJS that you are going to receive an stream of Post[], in other words, an Array<Post>.

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

If you wanna filter the array, you may do something like:

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

这篇关于使用带有RxJS的Angular 5可以看到带有过滤器的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆