将http响应映射到typeScript对象

问题描述 投票:0回答:2

我正在尝试将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}
]
angular typescript rxjs angular7
2个回答
0
投票

首先,您需要一种将这些值实际放入您的班级的方法。让我们只接受构造函数中的那些。

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))

0
投票

如果您希望在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));   
}
© www.soinside.com 2019 - 2024. All rights reserved.