2017-07-20 38 views
0

我有一個對象數組,我想根據大小這是對象的屬性進行排序。對象由{name,size}組成。我想根據大小對元素進行排序。OrderBy Pipe不適用於agular 4中的對象數組嗎?

服務:

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> 

+0

Angular2 +沒有'OrderByPipe' https://angular.io/guide/pipes#no-filter-pipe –

+0

角犯規什麼從盒子中提供'orderBy'管道.. –

回答

1

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