我收到此错误:
Cannot read property 'sort' of undefined
不确定这是怎么回事。页面功能正常,但我想摆脱错误。所以说,我相信这是从我的定制管道和它的使用。我有一个管道如下:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortby'
})
export class SortbyPipe implements PipeTransform {
transform(array: any[], field: string): any[] {
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
然后组件是这样的:
import { Component, OnInit } from '@angular/core';
import { GetEmailsService } from '../../services/get-emails.service';
import { GroupPipe } from '../../pipes/group.pipe';
@Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
providers: [GroupPipe]
})
export class EmailsComponent implements OnInit {
results: any;
grouped: any;
constructor(
private getEmailsService: GetEmailsService,
private groupPipe: GroupPipe
) {}
ngOnInit(): void {
this.getEmailsService.emailsAPI().subscribe(
data => {
const firstChar: any = null;
this.results = data;
this.grouped = this.groupPipe.transform(this.results, 'key');
}
);
}
}
我的模板如下所示:
<div class="row mb-5" *ngFor="let groups of grouped | sortby:'key'">
<div class="col-md-12">
<h1 class="rolodex">{{groups.key}}</h1>
</div>
<div class="col-md-12">
<div class="row">
<div class="col-sm-6 mb-3" *ngFor="let email of groups.value">
...do some stuff here
</div>
</div>
</div>
</div>
我尝试使用*ngFor="let groups of grouped? | sortby:'key'"
和*ngFor="let groups? of grouped | sortby:'key'"
解决此问题,但它不起作用并完全破坏了所有内容。关于这里发生了什么的任何建议?
答案 0 :(得分:0)
基于@JB Nizets的评论,我这样做了:
从模板中删除| sortby:'key'
,然后修改我的组件以在组件级别使用管道:
import { Component, OnInit } from '@angular/core';
import { GetEmailsService } from '../../services/get-emails.service';
import { Pipe, PipeTransform } from '@angular/core';
import { GroupPipe } from '../../pipes/group.pipe';
import { SortbyPipe } from '../../pipes/sortby.pipe';
@Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
providers: [
GroupPipe,
SortbyPipe
]
})
export class EmailsComponent implements OnInit {
results: any;
grouped: any;
constructor(
private getEmailsService: GetEmailsService,
private groupPipe: GroupPipe,
private sortbyPipe: SortbyPipe
) {}
ngOnInit(): void {
this.getEmailsService.emailsAPI().subscribe(
data => {
this.results = data;
this.grouped = this.sortbyPipe.transform(this.groupPipe.transform(this.results, 'key'), 'key');
}
);
}
}