2015-05-08 77 views
2

創建工廠「resInterceptor」,並使用在工廠外定義的函數(requestInterceptor,responseInterceptor)。它在函數內部發生錯誤'$ q is not defined'。但我只想這樣做。請建議如何在requestInterceptor和responseInterceptor中訪問$ q。

angular.module('resModule', ['ngResource', 'ngCookies']) 
.factory('resInterceptor', ['$rootScope', '$q', '$location', resInterceptor]); 

function resInterceptor($rootScope, $q, $location) { 
    return { 
     request: requestInterceptor, 
     response: responseInterceptor, 
    }; 
} 

function requestInterceptor(config) { 
    return config || $q.when(config); //$q is not defined 
} 

function responseInterceptor(response) { 
    return response || $q.when(response); 
} 
+1

requestInterceptor定義在不同的範圍內。這顯然不起作用。 –

回答

6

爲了這個工作,你需要通過$q沿着明確,使requestInterceptor返回您的實際回調函數:

function resInterceptor($rootScope, $q, $location) { 
    return { 
    request: requestInterceptor($q), 
    .. 
    }; 
} 

function requestInterceptor($q) { 
    return function (config) { 
    return config || $q.when(config); 
    }; 
} 

當然,這將是,如果你不那麼複雜簡單地將函數內聯到首先定義$q的相同範圍內。

4
angular.module('resModule', ['ngResource', 'ngCookies']) 
.factory('resInterceptor', ['$rootScope', '$q', '$location', resInterceptor]); 

function resInterceptor($rootScope, $q, $location) { 
    return { 
     request: requestInterceptor, 
     response: responseInterceptor, 
    }; 

    function requestInterceptor(config) { 
     return config || $q.when(config); //$q is defined :) 
    } 

    function responseInterceptor(response) { 
     return response || $q.when(response); 
    } 
}