简体   繁体   English

将 http 响应映射到 typeScript object

[英]Mapping http response to typeScript object

I am trying to convert API response (json string array) to typescript object but not able to achieve.我正在尝试将 API 响应(json 字符串数组)转换为 typescript object 但无法实现。 I tried to add map function but not able to use it properly.我尝试添加 map function 但无法正常使用。

Sample API response is ["Paris","London","New York"]示例 API 响应为 ["Paris","London","New York"]

my City class is like this我的城市class是这样的

export class City { Name:string; 
                    isAvailable: boolean;
                  }

My function我的 function

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;

         }

I expect output like我希望 output 喜欢

[
  {Name:"Paris",isAvailable:true},
  {Name:"London",isAvailable:true}, 
  {Name:"New York",isAvailable:true}
]

First, you'll need a way to actually put those values in your class.首先,您需要一种将这些值实际放入 class 的方法。 Let's just accept those in the constructor.让我们在构造函数中接受那些。

export class City {
  Name: string; 
  isAvailable: boolean;

  constructor(name: string, isAvailable: boolean) {
    this.Name = name
    this.isAvailable = isAvailable
  }
}

Now, assuming response is your JSON string, then first you want to parse the JSON string and cast it to the format you expect (which is string[] ).现在,假设response是您的 JSON 字符串,那么首先您要解析 JSON 字符串并将其转换为您期望的格式(即string[] )。

Then map over it to create what you need.然后 map 在它上面创建你需要的东西。

const cities: string[] = JSON.parse(response)
const cityObjects = cities.map(name => new City(name, true))

If you wish to handle this within your RxJS pipeline, this is what you can do.如果您希望在 RxJS 管道中处理此问题,您可以这样做。 We use the RxJS map operator to transform the response into an array of City objects.我们使用 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));   
}

You can map data automatically with a lightweight package called tapi.js您可以使用名为 tapi.js 的轻量级 package 自动 map 数据

npm i -D tapi.js

And then you can map the object automatically in a lot of ways, since you are mapping JSON data you can do so as such然后您可以通过多种方式自动 map object,因为您正在映射 JSON 数据,您可以这样做

http.YOUR_REQUEST
    .as(YourClass)
    .[then/pipe/whatever](typedObject => { ... })

You can read the docs for more info.您可以阅读文档以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM