对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屋!