RXJS Observable 数组的简单过滤器 [英] Simple filter on array of RXJS Observable
问题描述
我使用 Angular2 开始我的项目,开发人员似乎推荐使用 RXJS Observable 而不是 Promises.
I am starting my project with Angular2 and the developers seem to recommend RXJS Observable instead of Promises.
我已经实现了从服务器检索元素(史诗)列表.但是如何通过使用例如 id 来过滤元素?
I have achieved to retrieve a list of elements (epics) from the server. But how can I filter the elments by using for example an id?
以下代码是从我的应用程序中提取的,现在显示了最终的工作解决方案.让我们希望它可以帮助某人.
The following code is an extraction from my app and shows now the final working solution. Let's hope it helps someone.
@Injectable()
export class EpicService {
private url = CONFIG.SERVER + '/app/'; // URL to web API
constructor(private http:Http) {}
private extractData(res:Response) {
let body = res.json();
return body;
}
getEpics():Observable<Epic[]> {
return this.http.get(this.url + "getEpics")
.map(this.extractData)
.catch(this.handleError);
}
getEpic(id:string): Observable<Epic> {
return this.getEpics()
.map(epics => epics.filter(epic => epic.id === id)[0]);
}
}
export class EpicComponent {
errorMessage:string;
epics:Epic[];
epic:Epic;
constructor(
private requirementService:EpicService) {
}
getEpics() {
this.requirementService.getEpics()
.subscribe(
epics => this.epics = epics,
error => this.errorMessage = <any>error);
}
// actually this should be eventually in another component
getEpic(id:string) {
this.requirementService.getEpic(id)
.subscribe(
epic => this.epic = epic,
error => this.errorMessage = <any>error);
}
}
export class Epic {
id: string;
name: string;
}
预先感谢您的帮助.
推荐答案
您需要过滤实际的数组而不是环绕它的 observable.因此,您将把 Observable 的内容(它是一个 Epic[]
)映射到一个过滤后的 Epic
.
You'll want to filter the actual array and not the observable wrapped around it.
So you'll map the content of the Observable (which is an Epic[]
) to a filtered Epic
.
getEpic(id: string): Observable<Epic> {
return this.getEpics()
.map(epics => epics.filter(epic => epic.id === id)[0]);
}
然后你可以订阅
到getEpic
并用它做任何你想做的事情.
Then afterwards you can subscribe
to getEpic
and do whatever you want with it.
这篇关于RXJS Observable 数组的简单过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!