Angular - 无法读取 null 的 属性 'sort'
Angular - Cannot read property 'sort' of null
我正在对一些数据使用排序方法,据我所知,排序是 "activated" 在实际数据进入之前,虽然它有效,但它在控制台中留下了一些错误:ERROR TypeError: Cannot read property 'sort' of null.
<ng-container *ngFor="let attendee of (listOfAttendees$ | async | sort:'lastName': 'firstName':'asc')">
<div class="attendees-list__item d-flex">
<div class="attendees-list__item-name course-details-attendees col-4 col-md-4 text text-cooler-grey align-self-center pl-3">
{{ attendee?.lastName }}, {{ attendee?.firstName }}
</div>
</div>
</ng-container>
有什么好的地方可以移动排序函数,使其不提供 null
输出?
你能编辑 observable 吗?
如果是这样,您可以发出一个空数组而不是空值。
那应该可以防止 TypeError。
我建议编辑可观察对象,这样您就不必在模板内部进行排序
@Component({...})
export class MyComponent {
listOfAttendees$: Observable<Attendant[]>;
sortedAttendees$ = this.listOfAttendees$.pipe(
map(attendees => attendees ? attendees.sort((a, b) => {
const lastname = a.lastName.localeCompare(b.lastName);
return lastname === 0 ? a.firstName.localeCompare(b.firstName) : lastname;
}) : null)
)
}
并在您的模板中
<ng-container *ngFor="let attendee of sortedAttendees$ | async">
我正在对一些数据使用排序方法,据我所知,排序是 "activated" 在实际数据进入之前,虽然它有效,但它在控制台中留下了一些错误:ERROR TypeError: Cannot read property 'sort' of null.
<ng-container *ngFor="let attendee of (listOfAttendees$ | async | sort:'lastName': 'firstName':'asc')">
<div class="attendees-list__item d-flex">
<div class="attendees-list__item-name course-details-attendees col-4 col-md-4 text text-cooler-grey align-self-center pl-3">
{{ attendee?.lastName }}, {{ attendee?.firstName }}
</div>
</div>
</ng-container>
有什么好的地方可以移动排序函数,使其不提供 null
输出?
你能编辑 observable 吗? 如果是这样,您可以发出一个空数组而不是空值。 那应该可以防止 TypeError。
我建议编辑可观察对象,这样您就不必在模板内部进行排序
@Component({...})
export class MyComponent {
listOfAttendees$: Observable<Attendant[]>;
sortedAttendees$ = this.listOfAttendees$.pipe(
map(attendees => attendees ? attendees.sort((a, b) => {
const lastname = a.lastName.localeCompare(b.lastName);
return lastname === 0 ? a.firstName.localeCompare(b.firstName) : lastname;
}) : null)
)
}
并在您的模板中
<ng-container *ngFor="let attendee of sortedAttendees$ | async">