如何将对象中的对象转换为Angular类(类型) [英] How to cast object in object into Angular Class (Type)
本文介绍了如何将对象中的对象转换为Angular类(类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在下面的示例中将obj.category
转换为Category
类型?
How can I cast obj.category
into Category
type in example below?
我需要它来设置下拉菜单中的选定选项.
I need this to set selected options in dropdown.
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类(类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文