typescript 如何使用 rxjs 6 对 Angular 6 中的 Observable<Item[]> 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50275834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you sort an Observable<Item[]> in Angular 6 with rxjs 6?
提问by djangojazz
I just want to sort data on an observable of my class type 'Category'. So Observable < Category[] > I want to sort.
我只想对我的类类型“类别”的可观察数据进行排序。所以 Observable < Category[] > 我想排序。
So I upgraded to Angular6 and rxjs6 with it. One issue that is probably simple Typescript that I do know is how do I just do a 'sort' operation like:
所以我用它升级到 Angular6 和 rxjs6。我所知道的一个可能很简单的 Typescript 问题是我如何进行“排序”操作,例如:
sort((x,y) => x.description < y.description ? -1 : 1)
Inside of the new Angular6? I used to do this in 5
在新的 Angular6 里面?我曾经在 5 中这样做过
var response = this.http.get<Category[]>(this.endpoint);
.map((result: Response) => this.alphabetize(result));
alphabetize = (result: Response) => this.Categories = result.json()
.sort((x,y) => x.description < y.description ? -1 : 1)
And it worked fine. Now in the HttpCLIENTModule and HttpClient that Angular wants you to use it is simpler:
它工作得很好。现在在 Angular 希望你使用的 HttpCLIENTModule 和 HttpClient 中,它更简单:
var data = this.http.get<Category[]>(this.endpoint);
I just put the magic <(object)> before my endpoint and it does it for me. Cool. But I am not seeing how you get inside the object easily to sort from it with Source, Pipe, from, of. I know it is probably something simple I just don't know the syntax for.
我只是将魔法 <(object)> 放在我的端点之前,它为我完成了。凉爽的。但是我没有看到您如何轻松地进入对象内部以使用 Source、Pipe、from、of 对其进行排序。我知道这可能很简单,我只是不知道语法。
采纳答案by Estus Flask
It is:
它是:
this.http.get<Category[]>(this.endpoint).pipe(
map(results => results.sort(...))
);
Or since sort
modifies existing array, it's more semantically correct to provide side effects in do
/tap
:
或者由于sort
修改了现有数组,在do
/ 中提供副作用在语义上更正确tap
:
this.http.get<Category[]>(this.endpoint).pipe(
tap(results => {
results.sort()
})
);