对RXJS Observable数组进行简单过滤

Joh*_*nes 35 javascript observable rxjs typescript angular

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

预先感谢您的帮助.

Luk*_*itz 66

你想要过滤实际的数组,而不是包围它的observable.因此,您将Observable(即a Epic[])的内容映射到已过滤的内容Epic.

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

然后之后你可以subscribe到getEpic,做任何你想用它.


mtp*_*ltz 28

您可以使用flatMap和filter方法Observable而不是JS数组过滤器方法来执行此操作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!!!
Run Code Online (Sandbox Code Playgroud)

flatMap 将提供用于过滤的单一索引,然后您可以继续使用结果接下来发生的任何事情.

如果TypeScript抛出一个错误,指示无法比较字符串和数字,无论您==在过滤器中使用多少,只需按照Angular文档在过滤器中添加+before epic.id:

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

例:

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

  • 这比接受的答案更清晰,并充分利用Rx.正如作者所指出的那样,执行此操作的正确方法是使用`flatMap`. (2认同)

And*_*ich 5

带有修复的原始答案: Observables懒惰。你必须打电话subscribe告诉一个observable发送它的请求。

  getEpic(id:number) {
    return this.getEpics()
           .filter(epic => epic.id === id)
           .subscribe(x=>...);
  }
Run Code Online (Sandbox Code Playgroud)

更新到 Rxjs 6:

import {filter} from 'rxjs/operators';

getEpic(id:number) {
        return this.getEpics()
               .pipe(filter(epic => epic.id === id))
               .subscribe(x=>...);
      }
Run Code Online (Sandbox Code Playgroud)