我正在使用 Angular2 开始我的项目,开发人员似乎推荐 RXJS Observable 而不是 Promises。
我已经实现了从服务器检索元素列表(史诗)。但是如何通过使用例如 id 来过滤元素?
以下代码是从我的应用程序中提取的,现在显示了最终的工作解决方案。让我们希望它可以帮助某人。
@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;
}
预先感谢您的帮助。
原文由 Johannes 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要过滤实际的数组,而不是围绕它的 observable。因此,您会将 Observable 的内容(即
Epic[]
)映射到过滤后的Epic
。然后,您可以
subscribe
到getEpic
并随心所欲地使用它。