如果传入的json可以更改,如何动态分配对象?

时间:2019-03-15 13:31:03

标签: angular typescript

我上过课:

abstract class BaseItem {
    teamName: string;
}

export class ReleaseRoadmapItem extends BaseItem {
    startDate: Date;
    goal: string;
}

export class ControlPointRoadmapItem extends  BaseItem {
    workItemLink: string;
    isClosed: boolean;
}

Json数据可能以不同的方式变化。方法get()返回数组每个BaseItem类的类型。

export class ApiService {

    constructor(private readonly http: HttpClient) { }

    get(): Observable<BaseItem []>  {
        return this.http.get<BaseItem []>(`api/Roadmap);
    }
}

但是所有对象的类型都是BaseItem。如何初始化具有所需类型的Json对象?

例如Json数据:

[
  {
    "teamName":"companyName",
    "startDate": "01-01-2001",
    "goal": "goal"
  },
  {
    "teamName":"companyName",
    "workItemLink": "http://...",
    "isClosed": true
  }
]

我想得到结果。

ApiService.get().subscribe(x =>{
 let isRoadmapItem = x[0] is ReleaseRoadmapItem; // True
 let isPointRoadmapItem = x[1] is ControlPointRoadmapItem; // True
});

1 个答案:

答案 0 :(得分:0)

您可以尝试

export type RoadMapItem = ReleaseRoadmapItem | ControlPointRoadmapItem;

get(): Observable<RoadMapItem[]>  {
        return this.http.get<RoadMapItem[]>(`api/Roadmap);
    }

编辑:您的示例JSON数据不是数组。