【发布时间】:2016-12-29 14:19:52
【问题描述】:
有类似的问题,但没有一个答案对我有用,所以如果您不将此标记为重复,我将不胜感激(除非您让我回答确实解决问题的问题)
我有一个对象数组result:Array<Object>=[];,它与这些值一起返回:
在我的模板上,我想根据“喜欢”的数量对回复进行排序
<tr class *ngFor="let media of (result) | orderBy: 'data.likes.count'">
<td>
<img src={{media.data.images.standard_resolution.url}} height="100" width="100">
<p> {{media.data.likes.count}} </p>
</td>
</tr>
排序管道如下所示:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class SortPipe {
transform(array: Array<Object>, args: string): Array<Object> {
console.log("calling pipe");
if (array == null) {
return null;
}
array.sort((a: any, b: any) => {
if (a[args] < b[args] ){
//a is the Object and args is the orderBy condition (data.likes.count in this case)
return -1;
}else if( a[args] > b[args] ){
return 1;
}else{
return 0;
}
});
return array;
}
}
当我运行这段代码时,它会显示一个无序的响应,而不是根据喜欢对其进行排序。我应该指出,当我在管道上执行console.log(a[args]) 时,我得到了未定义,因此我可能没有正确读取对象字段中的值。
【问题讨论】:
-
响应看起来像吗? 1,10,11,12,13,14,15,16,17,18,19,2 等?仅仅因为您没有找到特定问题的解决方案,并不意味着其他答案是错误的?
-
抱歉,我不是这个意思。我的意思是,也许他们没有解决我面临的问题。为了回答您的问题,响应不受 orderBy pipe 的影响
-
SO 不是为了解决您的特定问题,即使它与可能不适合您的其他问题有关。但无论如何,我现在喝醉了,根本不在乎