【问题标题】:Using observable with sort data alphabetical使用 observable 按字母顺序排序数据
【发布时间】:2020-02-19 16:20:19
【问题描述】:

我使用 angular 8 和 asp.net 核心,所以我想在下拉列表中按字母顺序显示客户的姓名,从 api 服务,我找到了使用 observable 的唯一解决方案。还有其他方法可以实现吗?以及如何在 observable 中使用字母排序?

getAllcustomer() {
    return this._http.get<any>(this.myAppUrl + '/api/users/getcustomer', {responseType: 'json'} )
      .catch(this.errorHandler);
}

谢谢

【问题讨论】:

  • Observable 出了什么问题?
  • 您能提供有关响应数据的信息吗?
  • 接口是http所以你总是可以在c#中使用httpRequest。我会使用像wireshark或fiddler这样的嗅探器,看看当前请求是什么样子,然后创建你自己的代码来模仿当前代码。
  • @JuliusDzidzevičius 唯一的问题是我不熟悉 Observable 并且我不知道对它使用排序
  • ...seType: 'json'} ).pipe(map(res =&gt; res.sort()))res.sort()你可能需要修改

标签: c# angular asp.net-core observable


【解决方案1】:

您可以映射响应:

getAllcustomer() {
    return this._http.get<any>(this.myAppUrl + '/api/users/getcustomer', {responseType: 'json'} ).pipe(
  // assuming this API call gives you all the customers as an array of strings.
  map((response: any) => response.sort()), 
)
      .catch(this.errorHandler);
}

将此排序放在服务中是可选的,您也可以在组件本身中进行排序。

【讨论】:

    【解决方案2】:

    Observables,简单地说,是一个数据流,我们使用带有 API 调用的 observales(在你的例子中是 asp.net)。

    您要排序的是来自 API 的数据(响应),而不是 observable 本身。这里有两个选择,要么在服务本身中使用管道(Rxjs 运算符)进行排序,要么在组件中对常规 JS 数组进行排序(在其中订阅 observale)。

    在服务中

    getAllcustomer() {
        return this._http.get<any>(
                        this.myAppUrl + '/api/users/getcustomer',
                        {responseType: 'json'})
                .pipe(
                    map(res => res.sort((a,b) => a.name - b.name);),
                    catchError(this.errorHandler()) // use catch inside the pipe
                );
    }
    

    或在组件中

    this._customerService.getAllcustomer().subscribe(data => {
         const sortedData = data.sort((a,b) => a.name - b.name);
    })
    

    【讨论】:

      【解决方案3】:

      您可以使用sort() 方法来完成。引用from the MDN reference on sort():

      sort() 方法对数组的元素进行就地排序并返回排序后的数组。默认排序顺序是升序,将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列。

      试试这个:

      ma​​p 方法添加到您的导入中:

      import { map, catchError } from 'rxjs/operators';
      // ...
      

      使用管道连接 rxjs 方法

      getAllcustomer() {
        return this._http.get<any>(this.myAppUrl + '/api/users/getsuppliers', {responseType: 'json'} ).pipe(
          map(response => response.sort(),
          catchError(this.errorHandler));
      }
      

      假设响应结构是这样的:

      ['ccc', 'aba', 'aaa']

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多