[英]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.