Angularjs $resource 保存操作 return 承诺对象而不是响应的实际值
Angularjs $resource save action return promise object instead actual value of response
我定义了这个工厂来调用 rest 方法:
(function() {
'use strict';
angular.module('rgh').factory('Charge', Charge);
function Charge($resource) {
return $resource('rgh/charge/charge', {}, {
'save' : {
url : 'rgh/charge/charge',
method : 'POST'
}
});
}
})();
和这个 RestContrller
:
@RestController
@RequestMapping("/rgh/charge/charge")
public class ChargeResource {
@Autowired
private IChargeService chargeService;
@PostMapping
public long save(@RequestBody ChargeViewModel viewModelEntity) {
return chargeService.save(ModelMapper.map(viewModelEntity, Charge.class));
}
}
正如你所看到的保存方法returns保存对象的id,现在我想在angular控制器中得到这个返回的id:
(function() {
'use strict';
angular
.module('rgh')
.controller('ChargeDetailController', ChargeDetailController);
function ChargeDetailController(Charge) {
var vm = this;
vm.save = save;
function save() {
vm.isSaving = true;
Charge.save(vm.charge, onSaveSuccess, onSaveError);
}
var onSaveSuccess = function (result) {
vm.isSaving = false;
console.log(result);
};
var onSaveError = function () {
vm.isSaving = false;
};
}
})();
但是当我检查控制台时,我看到 $promise
对象而不是实际 ID。
您可以在 Angular 控制器中更改 save
方法,如下所示:
function save() {
vm.isSaving = true;
Charge.save(vm.charge).$promise
.then(function (result) {
console.log(result);
})
.catch(function (error) {
// Error
})
.finally(function() {
vm.isSaving = false;
});
}
我定义了这个工厂来调用 rest 方法:
(function() {
'use strict';
angular.module('rgh').factory('Charge', Charge);
function Charge($resource) {
return $resource('rgh/charge/charge', {}, {
'save' : {
url : 'rgh/charge/charge',
method : 'POST'
}
});
}
})();
和这个 RestContrller
:
@RestController
@RequestMapping("/rgh/charge/charge")
public class ChargeResource {
@Autowired
private IChargeService chargeService;
@PostMapping
public long save(@RequestBody ChargeViewModel viewModelEntity) {
return chargeService.save(ModelMapper.map(viewModelEntity, Charge.class));
}
}
正如你所看到的保存方法returns保存对象的id,现在我想在angular控制器中得到这个返回的id:
(function() {
'use strict';
angular
.module('rgh')
.controller('ChargeDetailController', ChargeDetailController);
function ChargeDetailController(Charge) {
var vm = this;
vm.save = save;
function save() {
vm.isSaving = true;
Charge.save(vm.charge, onSaveSuccess, onSaveError);
}
var onSaveSuccess = function (result) {
vm.isSaving = false;
console.log(result);
};
var onSaveError = function () {
vm.isSaving = false;
};
}
})();
但是当我检查控制台时,我看到 $promise
对象而不是实际 ID。
您可以在 Angular 控制器中更改 save
方法,如下所示:
function save() {
vm.isSaving = true;
Charge.save(vm.charge).$promise
.then(function (result) {
console.log(result);
})
.catch(function (error) {
// Error
})
.finally(function() {
vm.isSaving = false;
});
}