Angular RXJS如何将RESTAPI响应映射到应用程序中的模型?
主要的回应模式是:Angular RXJS如何将RESTAPI响应映射到应用程序中的模型?,angular,rxjs,Angular,Rxjs,主要的回应模式是: export interface TestDataState { userDetails: UserDetails | null; locationDetails: LocationDetails | null; } 每个接口: export interface UsersDetails { name: string; surname: string; age: number; colorEyes: string;
export interface TestDataState {
userDetails: UserDetails | null;
locationDetails: LocationDetails | null;
}
每个接口:
export interface UsersDetails {
name: string;
surname: string;
age: number;
colorEyes: string;
id: number;
work: string;
}
export interface LocationDetails {
city: string;
building: string;
departmentId: number;
floor: number;
deskId: number;
}
服务:
public loadUserDataFromApi(): Observable<TestDataState> {
return this.httpClient.get<ResponseData<TestDataState>>(
`http://api.com/test`
).pipe(
map(.......)
);
}
问题:
可以在loadUserDataApi方法中映射它?您可以这样做:
public loadUserDataFromApi(): Observable<TestDataState> {
return this.httpClient.get<ResponseData>(
`http://api.com/test`
).pipe(
map(res => {
let userDetails = {
name: res.data.name,
surname: res.data.surname,
age: res.age,
colorEyes: res.data.colorEyes,
id: res.data.id,
work: res.data.work
};
let locDetails = res.data.location;
return {
userDetails: userDetails as UserDetails,
locationDetails: locDetails as LocationDetails
} as TestDataState
})
);
}
}
public loadUserDataFromApi():可观察{
返回this.httpClient.get(
`http://api.com/test`
).烟斗(
地图(res=>{
让用户详细信息={
名称:res.data.name,
姓氏:res.data.姓氏,
年龄:res.age,
colorEyes:res.data.colorEyes,
id:res.data.id,
工作:res.data.work
};
让locDetails=res.data.location;
返回{
userDetails:userDetails作为userDetails,
locationDetails:locationDetails作为locationDetails
}作为TestDataState
})
);
}
}
但是:
如果您对后端交付数据的方式有影响,那么您应该使用一个用户模型,就像您在http响应中使用位置一样,并将其嵌套在数据对象中。
那么您的代码就不需要那么冗长了,它看起来更像这样:
public loadUserDataFromApi(): Observable<TestDataState> {
return this.httpClient.get<ResponseData>(
`http://api.com/test`
).pipe(
map(res => {
return {
userDetails: res.data.userDetails as UserDetails,
locationDetails: res.data.location as LocationDetails
} as TestDataState
})
);
}
}
public loadUserDataFromApi():可观察{
返回this.httpClient.get(
`http://api.com/test`
).烟斗(
地图(res=>{
返回{
userDetails:res.data.userDetails作为userDetails,
locationDetails:res.data.location作为locationDetails
}作为TestDataState
})
);
}
}
我也不明白为什么要将TestDataState作为类型嵌入ResponseData中,因为后端接收的类型是ResponseData,而您想要返回的可观察类型是TestDataState,所以我也改变了这一点
这是一个Stackblitz,您可以使用它,还可以进行真正的api调用:
干杯当然可以。如果你告诉我api响应,我会告诉你如何映射。json看起来像什么?谢谢!我用api的json响应更新了我的问题。对我来说,最好的解决方案是将它映射到一个通用模型->TestDataState。我想将其解析为TestDataState接口,它包含两个接口:用户和位置。就像问题中提到的那样。有操作员合并它吗?
public loadUserDataFromApi(): Observable<TestDataState> {
return this.httpClient.get<ResponseData>(
`http://api.com/test`
).pipe(
map(res => {
return {
userDetails: res.data.userDetails as UserDetails,
locationDetails: res.data.location as LocationDetails
} as TestDataState
})
);
}
}