我上过课:
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
});
答案 0 :(得分:0)
您可以尝试
export type RoadMapItem = ReleaseRoadmapItem | ControlPointRoadmapItem;
get(): Observable<RoadMapItem[]> {
return this.http.get<RoadMapItem[]>(`api/Roadmap);
}
编辑:您的示例JSON数据不是数组。