C# 使用按字母顺序排序的可观察数据

C# 使用按字母顺序排序的可观察数据,c#,angular,asp.net-core,observable,C#,Angular,Asp.net Core,Observable,我正在使用angular 8和asp.net core,因此我想在下拉列表中按api服务的字母顺序显示客户的姓名,我找到了使用observable的唯一解决方案。有没有其他方法来实现这一点?我如何在observable中使用字母排序 getAllcustomer() { return this._http.get<any>(this.myAppUrl + '/api/users/getcustomer', {responseType: 'json'} ) .cat

我正在使用angular 8和asp.net core,因此我想在下拉列表中按api服务的字母顺序显示客户的姓名,我找到了使用observable的唯一解决方案。有没有其他方法来实现这一点?我如何在observable中使用字母排序

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

谢谢

您可以映射响应:

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);
}
getAllcustomer(){
返回此值。_http.get(this.myAppUrl+'/api/users/getcustomer',{responseType:'json'})。管道(
//假设此API调用将所有客户作为字符串数组提供给您。
map((response:any)=>response.sort()),
)
.catch(this.errorHandler);
}

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

您可以使用
sort()
方法进行排序。引述:

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

试试这个:

将映射方法添加到导入中:

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));
}
getAllcustomer(){
返回此值。_http.get(this.myAppUrl+'/api/users/getsuppliers',{responseType:'json'})。管道(
映射(response=>response.sort(),
catchError(this.errorHandler));
}
假设响应结构如下所示:


['ccc'、'aba'、'aaa']
可观察对象,简而言之是一个数据流,我们将可观察对象与API调用一起使用(在您的案例中是asp.net)

您试图排序的是来自API的数据(响应),而不是可观测数据本身。这里有两个选项,要么在服务本身中使用管道(Rxjs操作符)排序,要么在组件中对常规JS数组排序(订阅观测数据的位置)

在职

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
            );
}

Observable有什么问题?你能提供关于响应数据的信息吗?接口是http,因此你可以始终使用c#中的httpRequest。我会使用wireshark或fiddler之类的嗅探器,查看当前请求的样子,然后创建自己的代码来模拟当前代码。@JuliusDzidzevičius唯一的问题是我没有熟悉Observable,不知道如何使用sort
…seType:'json'}).pipe(map(res=>res.sort())
res.sort()
您可能需要修改
this._customerService.getAllcustomer().subscribe(data => {
     const sortedData = data.sort((a,b) => a.name - b.name);
})