OrderBy Pipe 不处理 angular 4 中的对象数组?
OrderBy Pipe is not Working on array of objects in angular 4?
我有一个对象数组,我想根据对象的属性大小对它们进行排序。对象由 {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>
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;
}
}
我有一个对象数组,我想根据对象的属性大小对它们进行排序。对象由 {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>
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;
}
}