在Angular 6服务中过滤API数据

时间:2018-07-31 20:06:08

标签: angular typescript

所有示例仍参考Angular 2方法,NG6使用管道在服务内进行数据调用。

我服务中的此基本方法获取API返回的所有数据:

  getPatchGroups(): Observable<PatchGroup[]> {
    return this.http
      .get(API_URL + 'PatchGroups/ForApp/' + appId)
      .pipe(
        map(this.extractData),
        catchError(this.handleError)
      );
  }

现在,我需要将其拆分,以便我得到一个返回ID为-1的任何东西的调用,以及一个获取其他所有内容的调用。我需要在页面的不同区域中显示两组数据。

  getUngroupedPatchGroups(): Observable<PatchGroup[]> {
    return this.http
      .get(API_URL + 'PatchGroups/ForApp/' + appId)
      .pipe(
        map(this.extractData),  // where id < 0
        catchError(this.handleError)
      );
  }

  getGroupedPatchGroups(): Observable<PatchGroup[]> {
    return this.http
      .get(API_URL + 'PatchGroups/ForApp/' + appId)
      .pipe(
        map(this.extractData),  // where id > 0
        catchError(this.handleError)
      );
  }

过滤组件感觉很脏,但这是一种方法...创建一个自定义管道并应用于ngFor。性能等会更好地创建两个函数并对每个函数应用过滤器吗? NG 6.1.1的正确格式是什么?

编辑 如果将过滤器添加到extraData中,则会得到预期的结果。但是,不赞成使用“ Response”和“ body”为阴影命名?我该如何解决?

  private extractData(resp: Response) {
    const body = resp.json();
    return body.filter(body => body.id > 0);
  }

2 个答案:

答案 0 :(得分:1)

只用一个API调用并返回对象怎么样?

getPatchGroups(): Observable<{less: PatchGroup[], more: PatchGroup[]}> {
return this.http
  .get(API_URL + 'PatchGroups/ForApp/' + appId)
  .pipe(
    map(data => {
       const jsonData = data.json();
       return {less: jsonData.filter(d => d.id < 0), more: jsonData.filter(d => d.id > 0)};
    }),
    catchError(this.handleError)
  );
}

编辑:在组件中,根据发布的注释代码,您似乎将moreless重命名为groupedungrouped

 ngOnInit() {
   this.appsApiService.getPatchGroups().subscribe(pg => {
     this.ungrouped_patchGroups = pg.ungrouped;
     this.grouped_patchGroups = pg.grouped;
 });

或者在服务中为“少”和“多”有2个主题,在API调用后在tap或更确切地说,在subscribe中更新它们,并听从这些SubjectS创建的可观察对象。

答案 1 :(得分:0)

如果没有清晰的数据结构和应用程序视图,这将很难回答。根据您的问题和评论,我认为您将需要以下内容:

return this.http
           .get(API_URL + 'PatchGroups/ForApp/' + appId)
           .pipe(
             partition(patchGroup => patchGroup.id > 0),  // where id > 0
             catchError(this.handleError)
           );

partition方法采用一个谓词,该谓词是一个应用于迭代器中每个项目的函数。

相关问题