我有一個組件。Angular 2.問題與* ngFor,當我使用管道
@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
檢索一個對象數組。我輸出我的數組中component`s模板對象:
<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">
一切正常,我已經有了一個正確的結果:
但是,當我要排序我對象的數組,並使用我管,我沒有任何輸出:
I`ve我管F的得到了一個未定義的對象結^
@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;
}
}
http://cdn.meme.am/instances2/500x/4383577.jpg :) – Jacques