我有一个对象数组,我想根据作为对象属性的大小对它们进行排序。对象由{name,size}组成。我想根据大小对元素进行排序。
服务:
search(term: string): Observable<Array<Object>> {
let apiURL = `${this.apiRoot}?search=${term}`;
return this.http.get(apiURL)
.map(res => {
return res.json().results.map(items => {
return {name: items.name, population: items.population};
});
});
}
成分:
ngOnInit() {
this.myshared.getSaveBtnStatus().subscribe(data => this.isSuccess = data);
this.searchField = new FormControl();
this.searchField.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.myservice.search(term))
.subscribe(value => {
this.results = value;
console.log(this.results);
}
);
HTML:
<ul class="list-group">
<li class="list-group-item" *ngFor="let items of results">
{{items.name | orderBy : ['population'] }}
</li>
</ul>
答案 0 :(得分:2)
Angular 2+没有orderBy管道。但是很容易为你想要的东西建造一个。
这是一个简单的管道实现,以实现你想要的
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "orderBy"
})
export class OrderByPipe implements PipeTransform {
transform(value: any[], property: any, descending?: boolean): any {
if (!value || value.length) {
return value;
}
value.sort((first: any, second: any): number => {
return first[property] > second[property] ? 1 : -1;
});
if (descending) {
return value.reverse();
}
return value;
}
}