Service.js
myService.serviceName = function (userId) {
return $http({
method: 'POST',
url: '/someUrl'
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log('Service errorCallback');
console.log(response);
});
};
Controller.js
myService.ControllerName(data.id)
.then(function successCallback(data) {
//do processing here
}, function errorCallback(response) {
toaster.pop({
type: 'error',
title: 'Display Error Message!'
});
});
在服务中,我们在控制台中获取错误状态代码,即 -1
、-2
,并根据该代码向用户显示自定义错误消息。
- 如何将错误(消息/代码)从服务传递到 Controller ?
最佳答案
我首先想到的是接受来自 Controller 的回调。
myService.serviceName = function (userId) {
return $http({
method: 'POST',
url: '/someUrl'
})
};
在你的 Controller 中:
myService.serviceName(123).then(function(response) {
// Do the processing.
}, function(error) {
// Check the error and change the UI accordingly.
});
如果您需要在服务内进行处理,您可能需要使用 $q 服务。在这种情况下,您需要将其注入(inject)到您的服务中。
myService.serviceName = function (userId) {
var defer = $q.defer();
$http({
method: 'POST',
url: '/someUrl'
}).then(function (response) {
// Do the processing.
defer.resolve(response);
}).catch(function (error) {
defer.reject(error);
});
return defer.promise;
};
在你的 Controller 中:
myService.serviceName(123).then(function(response) {
// Indicate that everything went OK.
}, function(error) {
// Check the error and change the UI accordingly.
});
关于javascript - AngularJS - 将错误从服务传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529667/