【问题标题】:Angular ngResources request interceptorAngular ngResources 请求拦截器
【发布时间】:2015-02-01 12:22:06
【问题描述】:

为什么 angular $resources 没有请求和请求错误拦截器?

有什么办法吗?

文档内容:

interceptor - {Object=} - 拦截器对象有两个可选方法 - response 和 responseError。 response 和 responseError 拦截器都使用 http 响应对象调用。请参阅 $http 拦截器。

【问题讨论】:

    标签: angularjs request ngresource


    【解决方案1】:

    您可以按如下方式实现自己的拦截器。

    app.config(function ($httpProvider) {
        $httpProvider.interceptors.push('myInterceptor');
    });
    
    app.factory('myInterceptor', ['$q', function ($q) {
        return {
            request: function (config) {
                config.headers = config.headers || {};
                // insert code to populate your request header for instance
                return config;
            },
            response: function (response) {
                if (response.status === 403 || response.status === 401) {
                    // insert code to redirect to custom unauthorized page
                }
                return response || $q.when(response);
            }
        };
    }]);
    

    希望对你有所帮助。

    【讨论】:

    • 但这仅适用于使用 $http 发出的 Http 请求
    • 不,这也适用于 $resource。 $resource 包装 $http 以用于 RESTful Web API 场景。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2018-03-30
    • 2019-04-22
    相关资源
    最近更新 更多