I'm trying to call a Rails backend API and return some simple data - an array of models. For example, I have a car model, that has properties for make, year and price.
The Angular 2 model is similarly defined.
When making the http get call to the Rails app:
class CarsController < ApplicationController
respond_to :json
def index
respond_with Car.all.order(:make)
end
end
the rails app will return the data as a jSON array of objects that are each wrapped in an object:
[ { car: { year: 2017, Make: Honda, Model: Accord } },
{ car: { year: 2010, Make: Toyota, Model: Solara } }
]
etc
The Angular2 routine to call for, and convert the returned data:
getCars(): Observable<Car[]> {
return this.http.get(this.url)
.map(this.extractData)
.catch((res: Response ) => this.handleError(res));
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
does not work - it returns an empty object, as it expects the data to not have each object enclosed within another object.
How do I get Angular2 to do the right thing? How can I convert the returned data so Angular2 will populate my array of Cars correctly?
(I can't believe I can't find any reference to this issue when searching!)
Thanks.
I think the issue might be with that you are sending back an array as response instead of key value pair. If I recall correctly, AngularJS had special case when API was returning array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.