RxJS 6获取Observable数组的过滤列表
在我的ThreadService类中,我有一个函数 getThreads()
,该函数为我所有线程提供了 Observable< Thread []>
.
In my ThreadService class, I have a function getThreads()
that return me a Observable<Thread[]>
with all my threads.
现在,我想使用另一个函数版本,其线程由选定主题过滤:函数 getSelectedThemeThreads(theme:Theme)
.
Now, I would like to have another version of my function with my threads filtered by a selected theme : function getSelectedThemeThreads(theme: Theme)
.
我尝试使用运算符 map
和 filter
,但出现以下错误消息类型'Thread []上不存在属性'theme'代码>.
I tried with the operators map
and filter
but I have the following error message Property 'theme' does not exist on type 'Thread[]
.
在我正在处理的代码下面:
Below the code I am working on :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Thread } from '../models/thread.model';
import { Theme } from '../models/theme.model';
@Injectable({
providedIn: 'root'
})
export class ThreadService {
private threadsUrl = 'api/threads';
constructor(private http: HttpClient) { }
getThreads(): Observable<Thread[]> {
return this.http.get<Thread[]>(this.threadsUrl);
}
getSelectedThemeThreads(): Observable<Thread[]> {
return this.http.get<Thread[]>(this.threadsUrl).pipe(
map(threads => threads),
filter(thread => thread.theme.id === theme.id)
);
}
预先感谢您的帮助.
我以主要思想是在 map()
中进行过滤,因为过滤器将获得对象数组.
The main idea is to filter in the map()
as the filter will get an array of objects.
getSelectedThemeThreads(theme: string): Observable<Flower[]> {
return this.http.get<Flower[]>(this.threadsUrl).pipe(
map(result =>
result.filter(one => one.theme === theme)
)
)
}