【问题标题】:Get scope which the request is originated in interceptor获取请求来自拦截器的范围
【发布时间】:2015-02-06 12:31:44
【问题描述】:

在AngularJS响应错误拦截器中,有没有办法检索当前请求的范围?

module.controller('myController', function($http, $scope) {
    $scope.getData = function() {
        // This scope is which the request is originated
        $http.get('http://www.example.com/get', {
            params: { 'id': '1234' }
        }).success(function(data, status, headers, config) {
            // ...
        }).error(function(data, status, headers, config) {
            // ...
        });
    }
});

module.factory('myInterceptor', function($q) {
    return {
        'responseError': function(response) {
            // How can I get the scope of 'myController' here?
            return $q.reject(response);
        }
    };
});

【问题讨论】:

    标签: ajax angularjs interceptor angular-http-interceptors


    【解决方案1】:

    我认为您不能开箱即用地从工厂访问原始范围。 工厂是单例的,不建议在其中使用范围。 不过,我相信您可以将原始范围作为参数对象的一部分从您的控制器传递。

     params: { 'id': '1234', 'origScope': $scope }
    

    更新

    经过以下讨论... 我认为不是在这里访问范围。 您从拦截器发布事件并让范围或关联的控制器监听它。

    更多信息请参考此链接:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

    【讨论】:

    • params 对象将被解释为GET 请求中的查询字符串,对吧?将scope 传递给params 对象是否有意义?
    • 我想到了,你可以在实际发送请求之前delete config.params.origScope
    • 基本上就像我说的那样,将范围传递到工厂或服务根本不是一个好的设计。
    • 好吧,我正在尝试在responseError 处理程序中检索scope,因此请求已经发送。
    • 想知道为什么要访问拦截器中的范围会很有趣吗?
    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 2018-03-30
    • 2017-02-09
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多