如何在下面的示例中将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>
答案 0 :(得分:6)
可能的答案
export interface Category {
name: string;
prop: string;
}
export class Post {
category: Category[];
constructor(obj: any) {
this.category = obj.category as Category[];
}
}
`
答案 1 :(得分:0)
关键字tf.train.batch
允许我正确地将对象强制转换为所需的类,并修复了错误“ TS2322:类型'{}'无法分配给类型...”。谢谢!