如何将对象中的对象转换为Angular类(类型)

pel*_*ppl 5 typescript angular

在下面的示例中,如何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;
    }
}
Run Code Online (Sandbox Code Playgroud)

类别服务如下所示:

getCategories(): Promise<Category[]> {
    return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
  .then(response => response.json().map(obj => new Category(obj)))
  .catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)

api回应:

[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]
Run Code Online (Sandbox Code Playgroud)

模板:

<select multiple name="category" [(ngModel)]="obj.post.category">
    <option  *ngFor="let category of categories" [ngValue] = "category">
       {{category.name}}
    </option>
</select>
Run Code Online (Sandbox Code Playgroud)

sto*_*lan 8

可能的答案

export interface Category {
 name: string;
 prop: string;
}
export class Post {
    category: Category[];
    constructor(obj: any) {
        this.category = obj.category as Category[];
    }
}
`
Run Code Online (Sandbox Code Playgroud)