javascript - AngularJS - 将错误从服务传递到 Controller

标签 javascript angularjs

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/

相关文章:

javascript - 如何以 Angular 将自定义 header 添加到httpRequest

Javascript获取系统双击间隔?

javascript - 如何在循环中使用 selection.filter 方法将 D3 选择分组

angularjs - 错误: Can't set headers after they are sent. Node Expressjs

javascript - Angular SPA 中的 Google Analytics

javascript - AngularJs - 我如何才能仅在答案正确时显示答案

javascript - Jquery 为每个动态添加的选择框迭代函数

angularjs - $route.current 在尝试获取当前参数时未定义

javascript - 错误(模块 'app' 不可用!)

javascript - 使用 JavaScript Ajax 将表单数据发送到 Spring MVC