如何正确覆盖传递给`catch(function(errResponse){`函数)的`errResponse`? [英] How to correctly override `errResponse` which is passed to the `catch(function(errResponse){` function?

查看:129
本文介绍了如何正确覆盖传递给`catch(function(errResponse){`函数)的`errResponse`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制者:

angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        self.add = function() {
            BaseService.add.user(self.user)
                .catch(function(errorResponse) {
                    self.cerrorMessages = errorResponse.data;
                });
        };

这是我的BaseApp/工厂:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    });
                // if there are errors, rewrite the error messages
                }).catch(function(response) {
                     for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                         }
                     }
                });
            }
         };

当我尝试运行此代码并在控制器上调用self.add()时,出现错误,提示TypeError: Cannot read property 'catch' of undefined指向控制器中的行.catch(function(errorResponse) {.我猜这是因为没有then()函数.

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

我应该怎么做才能正确覆盖传递给控制器​​.catch()函数的errResponse参数(不具有.then()函数,因为如果成功则无需执行任何操作)?

What should I do to properly override the errResponse parameter which is passed to the controller's .catch() function (without having a .then() function because nothing is needed to be done if it is successful)?

推荐答案

当我尝试运行此代码并在控制器上调用self.add()时,出现错误,提示TypeError: Cannot read property 'catch' of 'undefined'指向控制器中的行.catch(function(errorResponse) {.我猜这是因为没有then()函数.

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of 'undefined' pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

那是一个错误的猜测. self.add()返回undefined,因为该函数省略了return语句.当函数忽略return语句时,它们返回原始值undefined.基本undefined上既没有.then方法也没有.catch方法.因此TypeError: Cannot read property 'catch'.

That is an erroneous guess. The self.add() returned undefined because the function omitted a return statement. When functions omit return statements, they return the primitive value undefined. There is neither a .then method nor a .catch method on the primitive undefined. Thus the TypeError: Cannot read property 'catch'.

返回< httpPromise:

It is important to return the httpPromise:

user: function(user) {
    //vvvv RETURN the promise
    return $http.post("/users/", user)
      .then(function successHandler(response) {
        //vvvv RETURN to chain
        return $http.post("/api-auth/login", user)
    }).then(function successHandler(response) {
        $window.location.href = "/";
    // if there are errors, rewrite the error messages
    }).catch(function rejectHandler(errorResponse) {
         for (prop in errorResponse.data) {
             if (prop == "email") {
                 errorResponse.data[prop] = "Please enter a valid email address.";
             } else if (prop == "username") {
                 errorResponse.data[prop] = "Please enter a valid username";
             }
         }
         //vvvv THROW to chain rejections
         throw errorResponse;
    });
}

同样重要的是,使用 throw statement .否则,拒绝将被转换成功.如果拒绝处理程序省略了throw语句,则它返回原始值undefined.这意味着拒绝将转换为成功解析为undefined值的成功承诺.随后它将跳过控制器中的.catch方法.

Also it is important to use a throw statement in rejection handlers. Otherwise the rejection will be converted to a success. If a rejection handler omits a throw statement, it returns a primitive value of undefined. This means the rejection will be converted to a successful promise that resolves to a value of undefined. It will subsequently skip the .catch method in the controller.

有关更多信息,请参见使用$q的角执行顺序.

For more information, see Angular execution order with $q.

这篇关于如何正确覆盖传递给`catch(function(errResponse){`函数)的`errResponse`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆