创建了一个工厂'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);
}
答案 0 :(得分:6)
为了实现这一点,您需要明确传递$q
并使requestInterceptor
返回您的实际回调函数:
function resInterceptor($rootScope, $q, $location) {
return {
request: requestInterceptor($q),
..
};
}
function requestInterceptor($q) {
return function (config) {
return config || $q.when(config);
};
}
当然,如果您只是将函数内联到第一个定义$q
的相同范围内,那么这将不那么复杂。
答案 1 :(得分: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);
}
}