【问题标题】:Filter api data in Angular 6 service在 Angular 6 服务中过滤 api 数据
【发布时间】:2018-08-01 21:54:34
【问题描述】:

所有示例仍然引用 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,我会得到我期望的结果。但是,不推荐使用响应,并且主体是影子命名的?我该如何解决这个问题?

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

【问题讨论】:

  • @peinearydevelopment 有趣的信息,但我仍然无法弄清楚如何根据返回的行的数据列之一中的值做出反应。 API 返回包含 7 个属性的记录,我如何根据其中一个属性的值做出反应?这些例子似乎都表明记录只有一个属性。

标签: angular typescript


【解决方案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;
 });

或者在服务中为“less”和“more”设置 2 个主题,在 API 调用后在 tap 或更确切地说是 subscribe 中更新它们,并监听从这些主题创建的 observables。

【讨论】:

  • 嗯,这看起来很有希望,但需要将 data.filter 调整为 data.json().filter。
  • 为你修改了答案,HTH
  • 无法分配第二个,显示为任何类型而不是强类型。 ` ngOnInit() { this.appsApiService.getPatchGroups() .subscribe(pg => this.ungrouped_pa​​tchGroups = pg.ungrouped, pg => this.grouped_pa​​tchGroups = pg.grouped); } `
  • 再次修改
【解决方案2】:

如果没有清楚地了解您的数据结构和应用程序,这将变得难以回答。根据您的问题和评论,我认为您需要以下内容:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-22
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2016-07-09
    相关资源
    最近更新 更多