如何在下面的示例中将 obj.category
转换为 Category
类型?
我需要它来设置下拉列表中的选定选项。
export class Category{
id: number;
name: string;
constructor(obj: any) {
this.id = obj.id;
this.name = obj.name;
}
}
export class Post {
category: Category[];
constructor(obj: any) {
this.category = obj.category;
}
}
类别服务如下所示:
getCategories(): Promise<Category[]> {
return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
.then(response => response.json().map(obj => new Category(obj)))
.catch(this.handleError);
}
API 响应:
[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]
模板:
<select multiple name="category" [(ngModel)]="obj.post.category">
<option *ngFor="let category of categories" [ngValue] = "category">
{{category.name}}
</option>
</select>
最佳答案
可能的答案
export interface Category {
name: string;
prop: string;
}
export class Post {
category: Category[];
constructor(obj: any) {
this.category = obj.category as Category[];
}
}
`
关于angular - 如何将对象中的对象转换为 Angular 类(类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47748170/