[英]Angular: Provider must define factory method
我是新手,现在有点迷茫。 我有一个提供程序来处理服务器是否发送响应,然后根据该响应执行一些操作。
这是提供商代码
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);
}]);
});
并引发错误:
提供程序“ httpProvider”必须定义$ get工厂方法。
任何想法?
编辑:
这是我的工厂现在的样子,它已经创建好了,但是我无法将其注入到配置中
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
};
});
好的,我已经能够修复它,我发现我以错误的方式创建了工厂,正确的方法是这样的:
define(['angular', './module'], function (angular, module) {
module.factory('httpInterceptor',['$q', '$rootScope', function ($q, $rootScope) {
return {
'request': function(config) {
return config;
},
'response': function (response) {
$rootScope.serverError = false;
return response;
},
'responseError': function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
}
};
}]);
});
在模块的配置中,我使用:
$httpProvider.interceptors.push('httpInterceptor');
谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.