【发布时间】:2016-06-01 03:03:50
【问题描述】:
我有一个组件。
@Component({
selector: 'top3',
templateUrl: 'dev/templates/top3.html',
pipes: [orderBy],
providers: [HTTP_PROVIDERS, ParticipantService]
})
export class AppTop3Component implements OnInit {
constructor (private _participantService: ParticipantService) {}
errorMessage: string;
participants: any[];
ngOnInit() {
this.getParticipants();
}
getParticipants() {
this._participantService.getParticipants()
.then(
participants => this.participants = participants,
error => this.errorMessage = <any>error
);
}
}
此组件使用名为_participantService 的服务。 _participantService 检索对象数组。我在组件的模板中输出我的对象数组:
<h2>Top 3</h2>
<table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#participant of participants | orderBy: '-score'; #i = index">
<td>{{i+1}}</td>
<td>{{participant.username}}</td>
<td>{{participant.score}}</td>
</tr>
</tbody>
</table>
我使用一个名为 orderBy 的管道和 *ngFor 指令。问题是当我不以这种方式使用管道和输出数组时:
<tr *ngFor="#participant of participants; #i = index">
一切正常,我得到了正确的结果:
但是当我想对对象的数组进行排序并使用我的管道时,我没有任何输出:
我的管道函数中有一个未定义的对象^
@Pipe({
name: 'orderBy',
pure: false
})
export class orderBy implements PipeTransform {
transform(arr: any[], orderFields: string[]): any {
console.log(arr);
orderFields.forEach(function(currentField: string) {
var orderType = 'ASC';
if (currentField[0] === '-') {
currentField = currentField.substring(1);
orderType = 'DESC';
}
arr.sort(function(a, b) {
return (orderType === 'ASC') ?
(a[currentField] < b[currentField]) ? -1 :
(a[currentField] === b[currentField]) ? 0 : 1 :
(a[currentField] < b[currentField]) ? 1 :
(a[currentField] === b[currentField]) ? 0 : -1;
});
});
return arr;
}
}
【问题讨论】:
标签: javascript arrays node.js angular javascript-objects