我正在使用 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;
}
预先感谢您的帮助。
最佳答案
您需要过滤实际数组而不是包裹在它周围的可观察对象。
因此,您会将 Observable 的内容(它是一个 Epic[]
)映射到过滤后的 Epic
。
getEpic(id: string): Observable<Epic> {
return this.getEpics()
.map(epics => epics.filter(epic => epic.id === id)[0]);
}
然后您可以订阅
getEpic
并用它做任何您想做的事情。
关于javascript - RXJS Observable 数组的简单过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37991713/