我是 Angular 新手,现在有点迷失。我有一个提供者来处理服务器是否发送响应,然后我根据它做一些事情。
这是提供商代码
define(['angular', '../module'], function (angular, module) {
return module.provider('httpProvider', ['$httpProvider', function ($httpProvider) {
var interceptor = ['$q', '$rootScope', function ($q, $rootScope) {
return {
response: function (response) {
$rootScope.serverError = true;
return response;
},
responseError: function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
},
};
}];
$httpProvider.interceptors.push(interceptor);
}]);
});
它会抛出错误:
Provider 'httpProvider' must define $get factory method.
有什么想法吗?
编辑:
这是我的工厂现在的样子,它创建得很好,但我无法将它注入(inject)到配置中
define(['angular', './module'], function (angular, module) {
module.factory('httpInterceptor', function () {
var interceptor = ['$q', '$rootScope', function ($q, $rootScope) {
return {
response: function (response) {
$rootScope.serverError = true;
return response;
},
responseError: function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
}
};
}];
return interceptor;
});
});
在模块配置中我这样使用它:
$httpProvider.interceptors.push('httpInterceptor');
但它实际上只是将一个字符串推送到数组(谁会想到这一点呢?D:),但什么也没发生。我已将工厂更改为始终将 serverError 设置为 true,因此我可以测试它,但它实际上不会执行任何操作,因此这意味着永远不会调用 response 或 responseError 函数。
有什么想法吗?
最佳答案
以下是创建拦截器的方法:
angular.module('myApp', []).
config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
});
angular.module('myApp').
factory('myInterceptor', function() {
return {
//interceptor object
};
});
关于javascript - Angular : Provider must define factory method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31988262/