我有一个组件。
@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 函数中有一个 undefined object ^
@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;
}
}
最佳答案
由于您使用 promise 异步加载数据,因此它们在开始时为空(在调用 then 方法中定义的第一个回调之前)。
您需要检查管道中的 are 参数是否为 null。如果是这样,你不应该执行“order by”处理......
当结果出现时,将使用数据再次调用管道(不会为空)。在这种情况下,您将能够对数据进行排序...
你可以试试这段代码:
@Pipe({
name: 'orderBy',
pure: false
})
export class orderBy implements PipeTransform {
transform(arr: any[], orderFields: string[]): any {
if (arr==null) {
return null;
}
(...)
}
}
关于javascript - Angular 2. *ngFor 问题,当我使用 Pipe 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507024/