简体   繁体   English

将数据从Rails API反序列化到Angular 2模型

[英]Deserializing data from Rails API to Angular 2 models

I'm trying to call a Rails backend API and return some simple data - an array of models. 我正在尝试调用Rails后端API并返回一些简单数据-模型数组。 For example, I have a car model, that has properties for make, year and price. 例如,我有一个汽车模型,它具有制造,年份和价格的属性。

The Angular 2 model is similarly defined. 类似地定义了Angular 2模型。

When making the http get call to the Rails app: 在http调用Rails应用程序时:

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: rails应用程序将以对象的jSON数组形式返回数据,每个对象都包装在一个对象中:

[ { 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: Angular2例程,用于调用并转换返回的数据:

  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? 如何让Angular2做正确的事? How can I convert the returned data so Angular2 will populate my array of Cars correctly? 如何转换返回的数据,以便Angular2可以正确填充我的Cars数组?

(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. 如果我没记错的话,当API返回数组时,AngularJS有特殊情况。

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

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