Reputation: 557
I am trying to convert API response (json string array) to typescript object but not able to achieve . I tried to add map function but not able to use it properly.
Sample API response is ["Paris","London","New York"]
my City class is like this
export class City { Name:string;
isAvailable: boolean;
}
My 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
[
{Name:"Paris",isAvailable:true},
{Name:"London",isAvailable:true},
{Name:"New York",isAvailable:true}
]
Upvotes: 2
Views: 7864
Reputation: 623
You can map data automatically with a lightweight package called tapi.js
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
http.YOUR_REQUEST
.as(YourClass)
.[then/pipe/whatever](typedObject => { ... })
You can read the docs for more info.
Upvotes: 0
Reputation: 42576
If you wish to handle this within your RxJS pipeline, this is what you can do. We use the RxJS map operator to transform the response into an array of City
objects.
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));
}
Upvotes: 3
Reputation: 187252
First, you'll need a way to actually put those values in your 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[]
).
Then map over it to create what you need.
const cities: string[] = JSON.parse(response)
const cityObjects = cities.map(name => new City(name, true))
Upvotes: 2