2015-05-08 33 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); 
    } 
}