我在使用 API 调用中的数据时遇到问题:我想使用检索到的数据来设置选中的复选框,但该组件在 API 响应之前已初始化,并且出现一些控制台错误:
ERROR TypeError: Cannot read property 'id' of undefined
我也使用解析器测试了行为,但是即使在初始化之前记录了响应数组,我也遇到了同样的问题:
组件.ts
...
export class RolesComponent implements OnInit {
flag: boolean = false;
simpleArr: object[] = [
{ userId: 1, id: 2 },
{ userId: 1, id: 3 },
{ userId: 1, id: 5 },
{ userId: 1, id: 7 }
]
permArr: object[] = [];
permArrResolved: object[] = [];
levels = [
{ name: 0, description: 'Creazione nuovo utente' },
{ name: 1, description: 'Reset password di qualsiasi utente' },
{ name: 2, description: 'Eliminazione di qualsiasi utente' },
{ name: 3, description: 'Modifica livello di qualsiasi utente' },
{ name: 4, description: 'Rinnovo delle licenze' },
{ name: 5, description: 'Gestione completa delle licenze' },
{ name: 6, description: 'Gestione completa dei clienti' },
{ name: 7, description: 'Gestione completa dei PC' }
];
constructor(private api: RolesApiService, private route: ActivatedRoute, ) {
this.api.getKeys().subscribe(keys => {
this.permArr = keys;
console.log(this.permArr);
this.flag = true
});
this.route.data.pipe(
map(data => data.cres)).subscribe((key) => {
this.permArrResolved = key;
console.log(this.permArrResolved);
});
}
ngOnInit() {
console.log('component is initialized');
}
}
组件.html
<form *ngIf="flag">
<h2>with permArr[0].id</h2>
<ng-container *ngFor="let level of levels">
<input type="checkbox" [checked]="level.name === permArr[0]?.id" />{{level.name}} - {{level.description}}
<br>
</ng-container>
<hr>
<h2>with simpleArr[level.name].id</h2>
<ng-container *ngFor="let level of levels">
<input type="checkbox" [checked]="level.name === simpleArr[level.name]?.id" />{{level.name}} - {{level.description}}
<br>
</ng-container>
<hr>
<h2>with permArr[level.name].id</h2>
<ng-container *ngFor="let level of levels">
<input type="checkbox" [checked]="level.name == permArr[level.name]?.id" />{{level.name}} - {{level.description}}
<br>
</ng-container>
<hr>
<h2>with permArr[level.name].id using resolver</h2>
<ng-container *ngFor="let level of levels">
<input type="checkbox" [checked]="level.name == permArrResolved[level.name]?.id" />{{level.name}} - {{level.description}}
<br>
</ng-container>
</form>
我制作了一个 stackblitz 演示来展示错误、api 服务、路由和我使用的解析器。在这里:https://stackblitz.com/edit/async-angular-resolver
如何解决这个问题?
编辑:使用安全操作符并不能解决该错误 EDIT2:在表单标签中使用 *ngIf 不能解决错误
最佳答案
这里已经有几个答案可以正确回答您所问的问题 - 它们对您不起作用的原因是您绑定(bind)的数据与您的 ID 不匹配。
您之前的问题基本上都在问同一件事:
- angular-nested-ngfor-tags-with-ngif-check-material-data-binding-async-issue
- angular-material-binding-property-does-not-work-cant-bind-to-checked-ngif
为了防止社区进一步浪费精力,我已经尽力编写您应该自己编写的调试代码。这显示了安全导航操作符如何修复模板问题,正如一些人已经建议的那样 - 用 *ngIf
包装也可以解决问题,并且我添加的值显示为什么你的复选框没有被选中。
https://stackblitz.com/edit/async-angular-resolver-hxxyw4?file=src/app/roles/roles.component.html
关于javascript - 组件初始化之前 Angular 加载异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649721/