AngularJS - 已解析的数据不会在嵌套状态组件中刷新

时间:2017-01-08 20:38:30

标签: javascript angularjs angular-ui-router angular-resource

我正在使用AngularJS 1.5,ui-router和angular-resource,我正在开发一个基于组件的应用程序。我有一个父状态,用于获取和更新数据,这个数据通过父状态解析器绑定到多个子状态。

当我在父组件控制器中手动更改数据时(例如vm.town.x = 666),一切正常,并且更改在子状态组件中可见。但是,当我从其他服务的响应中更改父组件控制器中的数据时(使用angular-resource),数据更改仅在父状态组件中可见。

州定义:

.state('town', {
  url: '/my-towns/:townId/',
  component: 'town',
  bindings: {
    town: 'townData'
  },
  resolve: {
    townData: function(Town, $stateParams) {
      return Town.get({
        townId: $stateParams.townId
      });
    }
  }
})

.state('town.detail', {
  url: 'detail',
  component: 'townDetail',
  bindings: {
    town: 'townData'
  }
})

父(镇)组件控制器定义:

function TownCmpController(TownServices,Town,BuildingUpgradeRest) {
  var vm = this;
  this.upgradeBuilding = function(data) {
     vm.town = BuildingUpgradeRest.update({townId:  vm.town.TownId,buildingId: data.building.BuildingId});
}

休息服务定义:

.factory('BuildingUpgradeRest',function($resource){
    return   $resource('api/public/v1/myaccount/towns/:townId/buildings/:buildingId/upgrade', {townId:'@townId', buildingId: '@buildingId'}, {
    'update': {
      method: 'PUT'
      }
    });
  })

'镇'对象绑定在两个组件中都是相同的

bindings: {
    town: '<'
  }

两个服务都返回相同的对象类型,两者都有效。

1 个答案:

答案 0 :(得分:1)

function TownCmpController(TownServices,Town,BuildingUpgradeRest) {
  var vm = this;
  this.upgradeBuilding = function(data) {
     BuildingUpgradeRest.update({townId:  vm.town.TownId,buildingId: data.building.BuildingId}).then(function (response) {
       vm.town = response;
     })
  }
}

您的服务返回承诺,因此您重新获得服务响应,然后设置vm.towns