【问题标题】:Error: promise is not defined错误:未定义承诺
【发布时间】:2015-04-08 05:24:51
【问题描述】:

我有一个工厂,它的功能是处理重定向状态代码。如果它看到状态码是302,就会把页面重定向到登录页面。

app.factory('redirectInterceptor', function($q,$location){
    return {
        responseError : function(response){
            return promise.then(
                function success(response) {
                    if(response.status === 302){
                        alert("success  " +response.status);
                        $location.path('/login.html');
                        return response;
                    }
                    else{
                        alert("success  "  +response.status);
                        return response; 
                    }
                },
                function error(response) {
                    if(response.status === 302){
                        alert("error " +response.status);
                        $location.path('/public/login.html');
                        return $q.reject(response);
                    }
                    else{
                        alert("error  " +response.status);
                        return $q.reject(response); 
                    }
                }
            );
        }
    }
});

app.config(['$httpProvider',function($httpProvider) {
    $httpProvider.interceptors.push('redirectInterceptor');
}]);

但是一旦服务器返回 302 就会出现错误。这里是

错误:未定义承诺

我做错了什么?

【问题讨论】:

  • 代码第 4 行的承诺从未被定义。
  • @pixelbits 是什么意思?我必须添加这个 var defer = $q.defer(); ?然后让它 defer.promise.then .. ?我一直在寻找可以帮助我的文章,我发现了这个thinkster.io/egghead/promises
  • 我不认为 302 是错误状态码。错误是 4xx 和 5xx
  • @chandermani 所以即使我使用http拦截器我也无法获得302?
  • 我认为在 302 上,浏览器会执行自动重定向。搜索 Angular $http 和 302 重定向。

标签: angularjs angular-promise


【解决方案1】:

你需要使用拦截器 有时您可能需要修改 HTTP 请求和响应。这可能有多种原因,例如为 HTTP 错误添加全局逻辑处理。使用拦截器,您可以在 Angular 应用程序中轻松完成此任务。

请参考:https://egghead.io/lessons/angularjs-using-angularjs-interceptors-with-http

另见此类似帖子AngularJS using an interceptor to handle $http 404s - promise not defined error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2018-01-31
    • 2019-07-26
    • 2017-10-06
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多