【发布时间】:2021-08-22 21:01:47
【问题描述】:
在我的 Angular-12 中,我的 api JSON 端点为:
{
"message": "Categories Successfully Retrieved.",
"error": false,
"code": 200,
"results": {
"categories": [{
"id": 2,
"name": "Computer",
"parent_id": null,
"child": [{
"id": 3,
"name": "Central Processing Unit",
"parent_id": 2,
},
{
"id": 4,
"name": "Hard Disc",
"parent_id": 2,
}
]
}]
}
}
服务:
public getCategories(): Observable<any> {
return this.http.get(this.api.baseURL + 'categories/list', this.httpOptions);
}
然后我就有了这个界面:
export interface ICategory {
id?: number;
name: string;
parent_id?: number;
child?: {id:number,name:string};
}
组件:
data = [];
allCategoryList: any[] = [];
category!: ICategory;
isLoading = false;
isSubmitted = false;
constructor(
private fb: FormBuilder,
private categoryService: CategoryService,
private router: Router,
private store: Store < AppState > ,
) {}
ngOnInit(): void {
this.isLoading = true;
this.loadCategory();
this.loadDatatable();
}
loadCategory() {
this.categoryService.getCategories().subscribe(
data => {
this.allCategoryList = data.results.categories;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
this.isLoading = false;
}
);
}
viewCategoryModal(row: any) {
this.category = row;
}
HTML:
我正在尝试使用下面的列表来显示每一行的详细信息:
<a class="btn btn-info btn-sm" (click)="editCategoryModal(row)" data-toggle="modal" data-target="#editCategoryModal">
Edit
</a>
<div class="modal fade" id="viewCategoryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> Category Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" *ngIf="category != undefined">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
Category: <strong>{{ Category.name || 'N/A' }}</strong>
</div>
</div>
</div>
<div class="col-md-12">
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th style="width: 100%">Contract</th>
</tr>
</thead>
<tbody *ngIf="category.child != undefined">
<tr *ngFor="let subcategory of category.child">
<td>{{subcategory.name}}</td>
</tr>
<tr *ngIf="!category.child">
<td colspan="4" class="text-center">
<span class="spinner-border spinner-border-lg align-center"></span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="hide()">Close</button>
</div>
</div>
</div>
</div>
父类别将有许多子子类别。因此,当用户单击父类别详细信息行时,它假设显示详细父类别及其所有子类别的模式,但我收到此错误:
错误 TS2322: 类型 '{ id: number;名称:字符串; }' 不可分配给类型 'NgIterable |空 |未定义'。
它突出显示:
我该如何解决这个问题?
谢谢
【问题讨论】:
标签: angular