如何使用Restangular建模AngularJS中的一对一关系

时间:2016-03-04 00:34:55

标签: angularjs restangular

我有一个companies集合,其country_id字段引用_id集合中的countries

Companies如下:

{
    name: "acme",
    address: "zossener straße 123",
    postalCode: "10961",
    city: "berlin",
    country_id: "56d58d68ab68b5cf3f72788e"
}

Countries如下:

{
    _id: "56d58d68ab68b5cf3f72788e",
    name: "Germany"
}

我尝试做的是将country_id Companies替换为Countries.name。因此,对于每个公司,我想要国家名称,而不是国家ID。我使用Restangular。我的控制器:

// creates a Restangular object of the 'companies' endpoint for later use
var Companies = Restangular.all('companies');

// for later pushing the countries
$scope.allCompanies = [];

// queries companies collection
Companies.getList().then(function(companies) {
  $scope.companies = companies;

  // iterates each company to get the country name
  for (var i = 0; i < $scope.companies.length; i++) {
    // prepares temp object to be pushed to $scope.allCompanies
    var buffer = {
      name: $scope.companies[i].name,
      address: $scope.companies[i].address,
      postalCode: $scope.companies[i].postalCode,
      city: $scope.companies[i].city,
      countryId: $scope.companies[i].country_id
    };

    // queries countries collection passing country_id
    var Country = Restangular.one('countries', $scope.companies[i].country_id);

    Country.get().then(function(country) {
      // sets country name for temp object based on country_id
      buffer.country = country.name;

      // pushes buffer to $scope.allCompanies
      $scope.allCompanies.push(buffer);
    });
  };

运行时,$scope.allCompanies会显示只有一个国家/地区的所有公司,这是分配给buffer的最后一个国家/地区。我认为承诺存在问题,但不确定。有帮助吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在函数中包装检索国家/地区的逻辑。这样,该函数保留buffer的正确引用,而不受i的更改影响:

// creates a Restangular object of the 'companies' endpoint for later use
var Companies = Restangular.all('companies');

// for later pushing the countries
$scope.allCompanies = [];

// queries companies collection
Companies.getList().then(function(companies) {
  $scope.companies = companies;
   function setCountryName(buffer){

    // queries countries collection passing country_id
    var Country = Restangular.one('countries', buffer.countryId);

    Country.get().then(function(country) {
      // sets country name for temp object based on country_id
      buffer.country = country.name;
    });
    return buffer;
   }

  // iterates each company to get the country name
  for (var i = 0; i < $scope.companies.length; i++) {
    // prepares temp object to be pushed to $scope.allCompanies
    var buffer = {
      name: $scope.companies[i].name,
      address: $scope.companies[i].address,
      postalCode: $scope.companies[i].postalCode,
      city: $scope.companies[i].city,
      countryId: $scope.companies[i].country_id
    };

      // pushes buffer to $scope.allCompanies
      $scope.allCompanies.push(setCountryName(buffer));
  };