我正在创建一个简单的论坛。
我正在寻找过滤帖子。我在 RxJS 中使用 .pipe 和 .filter 时遇到一些问题。
我试图:
- 从内存中检索 api 帖子列表
api/posts
,当与 http.get 一起使用时,它返回一个Observable<Post[]>
- 迭代每个
Post
in the Observable<Post[]>
并对其进行过滤,使其仅选择 id 为1
(只有一篇帖子有id1
存在)。
- 将任何错误或函数是否成功记录到控制台
The filter
不选择每个单独的部分Post[]
数组,而是选择Post[]
itself.
My code:
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[]'
在我看过的所有示例中,过滤器都没有这个问题。我正在想should迭代中的所有值Post[]
,数组,所以我可以将它作为Post
type.
回答后编辑
根据接受的答案,我的最终代码如下所示:
In 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', []))
);
}
In 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
)
;
}