我的应用中有一个通用API服务,可以向后端发出这样的请求:
post<T>(url: string, jsonObject: object): Observable<T> {
return this.http.post<T>(url, JSON.stringify(jsonObject));
}
我从我的组件中使用这样的方法并尝试将响应转换为特定模型:
this.apiService.post<SomeSpecificModel>('some/path/here', this.usernameForm.value)
.subscribe(
res => {
console.warn(res);
},
() => {
console.warn("error");
}
);
我的问题是API会返回如下内容:
{
code: some-string,
type: some-number,
data: []
}
data
属性是我想要在Angular中使用我的模型进行实体的实体。
我仍然希望能够访问我的组件中的code
和data
属性,但我不知道如何实现这一点。
我可以创建一个模仿API响应并具有通用数组属性的基本模型吗?像这样:
export class BaseModel<T> {
code: string;
type: number;
data: Array<T>;
}
然后像这样投射?
this.apiService.post<BaseModel<SomeSpecificModel>>(...
我试过了,但我没有收到任何构建错误,但SomeSpecificModel
上的属性未映射。
答案 0 :(得分:2)
尝试一下这个。
您的服务代码
public fetchData<T>(resourcePath: string):Observable<ResourceData<T>> {
return this.http.get<ResourceData<T>>(resourcePath);
}
您的组件代码
this.yourService.fetchData<DropDownDataItem>('/your/path/')
.map((response) => {
return {
count: response.count,
items: response.data
};
});
Inteface
export interface DropDownDataItem {
id: number;
name: string;
}
export interface ResourceData<T> {
data: T[];
limit?: number;
offset?: number;
count: number;
}
希望这有帮助