我在ConnectService中有这个功能。该函数每60秒检查一次连接:
class ConnectService {
static $inject = ["$http","$interval","$q"];
constructor(public $http, public $interval, public $q) { }
checkConnection = () => {
var self = this;
let checking = false;
self.isConnected().then(self.isConnectedHandler, self.isNotConnectedHandler);
this.$interval(function () {
// I need to somehow check if there has been
// a http response in the last minute and if
// so then return.
if (checking) return; else checking = true;
self.isConnected().then(self.isConnectedHandler, self.isNotConnectedHandler)
.finally(() => {
checking = false;
});
}, 60 * 1000);
}
}
isConnectedHandler = (response): void => { // }
isNotConnectedHandler = (response): void => { // }
}
app.service('connectService', ConnectService)
我有这个检查http响应的工厂方法:
app.factory('testInterceptor', ['$q', function ($q) {
return {
'response': function (response) {
// I need to somehow set a flag or communicate to
// the connection service not to do a check of a
// connection for 60 seconds
return response;
}
}
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('testInterceptor');
}])
我想要做的是,如果有成功的响应,那么连接检查将被禁用60秒。有谁知道如何在工厂和服务之间实现这种沟通?
答案 0 :(得分:2)
在这种情况下,我建议服务不会直接相互通信,甚至不会彼此了解。服务应尽可能分开。
在这种情况下,事件会更合适。
使用$rootScope.$emit
函数,您可以确保正在$rootScope
上收听该事件的任何侦听器都会知道该事件。
$emit
通过作用域层次结构向上调度事件名称,因为它是rootScope,它没有任何高级作用域,因此当您不确定作用域层次结构时,它是最有效的通信方式。
也不要忘记使用ConnectService中的$rootScope.$on
来听取事件。
app.factory('testInterceptor', ['$q', '$rootScope', function ($q, $rootScope) {
return {
'response': function (response) {
$rootScope.$emit('rootScope:success-response');
return response;
}
}
}]);
和连接服务:
class ConnectService {
static $inject = ["$http","$interval","$q", "$rootScope"];
constructor(public $http, public $interval, public $q, public $rootScope) {
$rootScope.$on('rootScope:success-response',(event, data) => {
// Delay the timer -> stop the interval and restart with delay
});
}
checkConnection = () => {
var self = this;
let checking = false;
self.isConnected().then(self.isConnectedHandler, self.isNotConnectedHandler);
this.$interval(function () {
// I need to somehow check if there has been
// a http response in the last minute and if
// so then return.
if (checking) return; else checking = true;
self.isConnected().then(self.isConnectedHandler, self.isNotConnectedHandler)
.finally(() => {
checking = false;
});
}, 60 * 1000);
}
}
isConnectedHandler = (response): void => { // }
isNotConnectedHandler = (response): void => { // }
}
app.service('connectService', ConnectService)