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

查看:20
本文介绍了如何正确覆盖传递给 `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:无法读取属性 '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 语句在拒绝处理程序中.否则拒绝将转换成功.如果拒绝处理程序省略了 throw 语句,它将返回 undefined 的原始值.这意味着拒绝将转换为 successful 承诺,该承诺解析为 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<的Angular执行顺序.

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

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

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