RXJS Observable 数组上的简单过滤器

新手上路,请多包涵

我正在使用 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 许可协议

阅读 1k
2 个回答

您需要过滤实际的数组,而不是围绕它的 observable。因此,您会将 Observable 的内容(即 Epic[] )映射到过滤后的 Epic

 getEpic(id: string): Observable<Epic> {
  return this.getEpics()
     .map(epics => epics.filter(epic => epic.id === id)[0]);
}

然后,您可以 subscribegetEpic 并随心所欲地使用它。

原文由 Luka Jacobowitz 发布,翻译遵循 CC BY-SA 4.0 许可协议

You can do this using the flatMap and filter methods of Observable instead of the JS array filter method in map .就像是:

 this.getEpics()
    .flatMap((data) => data.epics) // [{id: 1}, {id: 4}, {id: 3}, ..., {id: N}]
    .filter((epic) => epic.id === id) // checks {id: 1}, then {id: 2}, etc
    .subscribe((result) => ...); // do something epic!!!

flatMap 将为过滤提供奇异索引,然后您可以继续处理接下来发生的任何结果。

如果 TypeScript 抛出错误,表明您无法比较字符串和数字,无论您在过滤器中使用 == ,只需在 + epic.id 过滤器,根据 Angular 文档:

     .flatMap(...)
    .filter((epic) => +epic.id === id) // checks {id: 1}, then {id: 2}, etc
    .subscribe(...)

例子:

https://stackblitz.com/edit/angular-9ehje5?file=src%2Fapp%2Fapp.component.ts

原文由 mtpultz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题