使用带有 RxJS 的 Angular 5 和过滤器观察数组 [英] Observable of array with filter using Angular 5 with RxJS
问题描述
我正在创建一个简单的论坛.
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
- 遍历
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 anObservable<Post[]>
- Iterate through each
Post
in theObservable<Post[]>
and filter it so it only selects, says, each post with an id of1
(only one post with id1
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
)
;
}
推荐答案
Observables 是值流.您对 RXJS 说您将收到一个 Post[]
流,换句话说,一个 Array
.
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屋!