我有一个组件。
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('password');
$table->string('first_name', 20);
$table->string('last_name', 20);
$table->integer('class_id')
->unsigned()
->nullable();
$table->enum('type', ['admin', 'teacher', 'student']);
$table->rememberToken();
$table->timestamps();
此组件使用名为@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
指令的Pipe。问题是当我不以这种方式使用Pipe和输出数组时:
*ngFor
一切正常,我得到了正确的结果:
但是当我想对对象的数组进行排序并使用我的Pipe时,我没有任何输出:
我的Pipe函数中有一个未定义的对象^
<tr *ngFor="#participant of participants; #i = index">
答案 0 :(得分:3)
由于使用promise异步加载数据,因此它们在开头是空的(在调用then方法中定义的第一个回调之前)。
您需要检查管道中的are参数是否为空。如果是这样,你就不应该通过&#34;执行&#34;命令。处理...
当结果出现时,将使用数据再次调用管道(赢得“无”)。在这种情况下,您将能够对数据进行排序......
您可以尝试以下代码:
@Pipe({
name: 'orderBy',
pure: false
})
export class orderBy implements PipeTransform {
transform(arr: any[], orderFields: string[]): any {
if (arr==null) {
return null;
}
(...)
}
}
答案 1 :(得分:3)
根据管道文档(https://angular.io/docs/ts/latest/guide/pipes.html#!#jsonpipe)的示例,您错过了括号:
<tr *ngFor="#participant of (participants | orderBy: '-score'); #i = index">
答案 2 :(得分:0)
您可以改为在组件中定义一个空数组,而不是修改您的管道实现来处理null(即@Thierry的答案),而不是在组件中定义一个空数组:
participants = [];
当数据从服务器返回时,要么将项目推送到现有阵列,
.then(participants => this.participants.push(...participants),
或做你已做过的事情:分配一个新阵列。
请注意,...
是ES2015 feature。