gpt4 book ai didi

angular - 使用带有 RxJS 的 Angular 5 和过滤器观察数组

转载 作者:行者123 更新时间:2023-12-03 20:30:40 25 4
gpt4 key购买 nike

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

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

我试图:

  • api/posts 检索 in-memory-api 帖子列表,当与 http.get 一起使用时,它返回 Observable<Post[]>
  • 遍历每个 PostObservable<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', []))
    );
    }

    我的错误:
    Property 'id' does not exist on type 'Post[]'

    在我看过的所有示例中,过滤器都没有这个问题。我认为它应该遍历 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', []))
    );

    }

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

    最佳答案

    Observable 是值的流。您对 RXJS 说您将收到 Post[] 的流。 ,换句话说,一个 Array<Post> .

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

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

    关于angular - 使用带有 RxJS 的 Angular 5 和过滤器观察数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385805/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com