angular - 将 HTTP 响应映射到 TypeScript 对象
我正在尝试将 API 响应(JSON 字符串数组)转换为 TypeScript 对象,但无法实现。我尝试添加 map 函数,但无法正确使用它。
示例 API 响应是 ["巴黎","伦敦","纽约"]
我的 City 类是这样的
export class City { Name:string;
isAvailable: boolean;
}
我的功能
public getCities(queryId: string) : Observable<City[]> {
const url = apiUrl;
const response = this.http.get<string[]>(url)
.pipe(catchError(this.handleError));
//how can i add map method here to convert String to City object?
return response;
}
我期望的输出像
[
{Name:"Paris",isAvailable:true},
{Name:"London",isAvailable:true},
{Name:"New York",isAvailable:true}
]
答案#1
如果您希望在 RxJS 管道中处理此问题,您可以这样做。我们使用 RxJS 的 map 操作符将响应转换为 City 对象的数组。
public getCities(queryId: string) : Observable<City[]> {
const url = apiUrl;
return this.http.get<string[]>(url)
.pipe(
map((res) = {
return res.map(name => ({
Name: name,
isAvailable: true,
});
}),
catchError(this.handleError));
}
答案#2
首先,你需要一个方法将这些值真正放入你的类中。我们就在构造函数中接受这些值吧。
export class City {
Name: string;
isAvailable: boolean;
constructor(name: string, isAvailable: boolean) {
this.Name = name
this.isAvailable = isAvailable
}
}
现在,假设 response 是你的 JSON 字符串,那么首先你需要解析 JSON 字符串并将其转换为你预期的格式(即 string[])。
然后对其进行映射以创建你所需要的东西。
const cities: string[] = JSON.parse(response)
const cityObjects = cities.map(name => new City(name, true))
