简体   繁体   中英

Send 2 json from server to angularjs controller by 1 request

In a rails project, I have 1 controller and 2 model. I want send 1 request from angularjs to rails server and for response, get 2 json array, 1. first model. 2. seccond model.

Now I use below code, and get just 1 of 2 array:

Rails Contorller: tables_controller.rb :

class Api::V1::TablesController < Api::V1::BaseController
  def index
    @table = Table.all
    @mostagheltype = Mostagheltype.all
    //I can just send 1 of model.
    respond_with(Table.all)
  end
end

Angularjs Controller: table.js :

$scope.tables = Tables.index();

tableService.js :

'use strict';
var app = angular.module('tableService', ['ngResource']);

app.factory('Tables', function($resource) {
    return $resource('/api/tables.json', {}, {
        index: { method: 'GET', isArray: true}
    });
});

I can push 2 table in 1 array in rails controller and then recieve this from angular controller, like below:

array = []

Table.all.each do |table|
  array << { name: table.name, check: 1 }
end
Mostagheltype.all.each do |m|
  array << { name: mostagheltype.name, check: 2}
end
//I can seprate 2 array by `check` value in angularjs part.

but I want a solution that I send each array separate. How can I do this? Any idea?

Short answer no. You can't have two responses to one request. You can respond with an object that contains both arrays.

My is a little rusty. So this may be more psuedo code than ruby;

obj  = {} 
obj.array1 =[] 
obj.array2 =[] 

Then populate each array and return the object.

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.

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