在angular 6应用程序中,我使用"ng select"https://github.com/ng-select/ng-select#getting-启动选择框并触发"更改"事件以从API方法检索数据并将其分配给可观察对象,然后使用我的html中的异步管道来侦听此可观察对象的数组属性并将其显示在表中,尽管我正在表中检索数据,但在某个时刻它抛出了一个错误,因为该属性的计算结果为"null",
AgentBranchAssignmentComponent.html:72 ERROR TypeError: Cannot read property 'users' of null
at Object.eval [as updateDirectives] (AgentBranchAssignmentComponent.html:72)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
at checkAndUpdateView (core.js:10451)
at callViewAction (core.js:10692)
at execEmbeddedViewsAction (core.js:10655)
at checkAndUpdateView (core.js:10452)
at callViewAction (core.js:10692)
at execComponentViewsAction (core.js:10634)
at checkAndUpdateView (core.js:10457)
at callViewAction (core.js:10692)
因此,请告知:1) 为什么会发生这种错误,以及如何避免?2) 对于这种情况,这是最好的解决方案吗?3) 如果我清除了所选内容,如何清除表格?
这是和在html:中具有ngFor"ng-select"配置的表
<ng-select
(change)="getAgentsForBranch($event)"
[items]="branches">
</ng-select>
<tbody *ngIf="userPage && (userPage | async).users">
<tr *ngFor="let u of (userPage | async).users">
<td>{{u.firstName + " " + u.lastName}}</td>
<td>{{branchName}}</td>
</tr>
</tbody>
这是ts:
userPage: Observable<AllUserListPage>;
getAgentsForBranch(event) {
if(!event){
// here i am clearing the selction and want to clear data in the table also
this.branchName= '';
return;
}
const branchId = event.branchId;
this.branchName = event.name;
this.userPage = this.obexService.getUsersForBranch(branchId, 0, 50, 'OLDEST', true)
}
从外观上看,您似乎得到了它,因为您的可观察对象是未定义的。解决这个问题的简单方法是使用"elvis操作符"或可选的链接。
改为执行以下操作:(userPage | async)?.users
<tbody *ngIf="userPage && (userPage | async)?.users">
<tr *ngFor="let u of (userPage | async)?.users">
<td>{{u.firstName + " " + u.lastName}}</td>
<td>{{branchName}}</td>
</tr>
</tbody>
您还可以尝试将userPage
打印到console
,以验证您是否获得了所需的数据。或者,您可以在模板中执行{{ (userPage | async) | json }}
。
尝试将ng-container
与async
管道一起使用,当您有数据时,结果变量将提供数据
<ng-container *ngIf="userPage | async as result ">
<tbody >
<tr *ngFor="let u of result.users">
<td>{{u.firstName + " " + u.lastName}}</td>
<td>{{branchName}}</td>
</tr>
</tbody>
</ng-container>
查看这个演示