2015-02-06 91 views
2

在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); 
     } 
    }; 
}); 

回答

0

我不認爲您可以從開箱即可訪問原始範圍。 工廠是單身人士,不建議玩它的範圍。儘管如此,我相信你可以通過控制器傳遞原始範圍作爲param對象的一部分。

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

更新

下面的討論之後...... 我想,而不是在這裏訪問的範圍。 您從攔截器發佈事件並讓作用域或關聯的控制器監聽它。

請參閱此鏈接瞭解更多信息:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

+0

的'params'對象將被解釋爲查詢字符串'GET'請求,對不對?將'scope'傳遞給'params'對象是否合理? – 2015-02-06 04:02:48

+0

我想到了這一點,以及你可以在請求實際發送前刪除config.params.origScope' – 2015-02-06 04:08:25

+0

基本上如我所說,將範圍傳遞到工廠或服務並不是一個好的設計。 – 2015-02-06 04:09:34