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

How to model one-to-one relationships in AngularJS with Restangular

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

Companies如下:

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

Countries如下:

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

我想做的是将 Companiescountry_id 替换为 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的国家。我认为承诺有问题,但不确定。有什么帮助吗?提前致谢。

您可以将检索国家/地区的逻辑包装在一个函数中。这样,函数保持 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));
  };