我正在尝试将API响应(json字符串数组)转换为打字稿对象,但无法实现。我试图添加地图功能,但无法正常使用。
示例API响应为[“巴黎”,“伦敦”,“纽约”]
我的城市班级就是这样
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}
]
答案 0 :(得分: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))
答案 1 :(得分:2)
如果您希望在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));
}