代码之家  ›  专栏  ›  技术社区  ›  Fahad Subzwari

我不能用rxjs过滤器过滤记录?

  •  0
  • Fahad Subzwari  · 技术社区  · 1 年前

    angular 项目,我有 rxjs filter 我无法通过它过滤记录。我的功能在这里

    public getOrders(type: string, filterObj = {}, otherParams = {}): Observable<{ name: string; qt: number }[]> {
       return this.http.get(apiUrl, { params: { filter: JSON.stringify(filterObj), ...otherParams},
       })
       .pipe(map((res: any) => res.payload))
       .pipe(filter((order: any) => order.name && /\S/.test(order.name)));
    }
    

    但如果我喜欢这样,它就正常工作了。

    public getOrders(type: string, filterObj = {}, otherParams = {}): Observable<{ name: string; qt: number }[]> {
       return this.http.get(apiUrl, { params: { filter: JSON.stringify(filterObj), ...otherParams},
       })
       .pipe(map((res: any) => res.payload.filter((order: any) => order.name && /\S/.test(order.name))))
    }
    

    这里怎么了?

    2 回复  |  直到 1 年前
        1
  •  0
  •   Octavian Mărculescu    1 年前

    rxjs filter Array.filter .

    滤器 httpClient.get )

    Array.filter ,为了过滤掉数组中的某些元素,您确实需要一个方法,该方法返回一个数组,其中包含与您的过滤条件相对应的元素。因此,为了正确地完成这项工作,你可以这样写:

    public getOrders(
      type: string,
      filterObj = {},
      otherParams = {}
    ): Observable<{ name: string; qt: number }[]> {
      return this.http
        .get(apiUrl, {
          params: { filter: JSON.stringify(filterObj), ...otherParams },
        })
        .pipe(
          map((res: any) => res.payload),
          map((orders) =>
            orders.filter((order: any) => order.name && /\S/.test(order.name))
          )
        );
    }
    

    或者干脆省略第二个 map

        2
  •  0
  •   Antoniossss    1 年前

    看起来你的有效载荷是一个 array

    const arr:any = [];
    if(arr.name){///whatever}
    

    你的 filter 工作正常,你的代码写得不好。因此,正如我所写

    在angular项目中,我有一个rxjs过滤器,它不能正常工作 它应该这样做。

    是一个大胆的声明

    停止使用 any