Javascript angularjs longpolling for mail应用程序
我将用angular js创建一个邮箱,这样我就有了一个服务和一个管理邮件的控制器 服务Javascript angularjs longpolling for mail应用程序,javascript,jquery,angularjs,ajax,long-polling,Javascript,Jquery,Angularjs,Ajax,Long Polling,我将用angular js创建一个邮箱,这样我就有了一个服务和一个管理邮件的控制器 服务 app.service('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){ var updatedData; $interval(function(){ return $http.post('inc/get_mails.php?user='+'<?php
app.service('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){
var updatedData;
$interval(function(){
return $http.post('inc/get_mails.php?user='+'<?php echo $_SESSION['user']; ?>')
.success(function(response){
updatedData = response;
alert(updatedData);
$rootScope.$broadcast('got new mail!', { data: updatedData });
})
.error(function(err){console.log(err);});
},1000);
}]);
但我有一个问题,这项服务甚至没有运行一次。我该怎么办(
tnx您的服务中的代码没有被调用,您必须注入您的服务才能运行它。但是我认为在您的服务中创建一个方法来初始化您的代码是更好的做法,它更显式
app.factory('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){
var updatedData = [];
return {
init: init
}
function init() {
$interval(function(){
return $http.post('inc/get_mails.php?user='+'<?php echo $_SESSION['user']; ?>')
.success(function(response){
// check if their is a difference between this call and the last call
if (updatedData.length !== response.length) {
updatedData = response;
alert(updatedData);
$rootScope.$broadcast('got new mail!', { data: updatedData });
}
})
.error(function(err){console.log(err);});
},1000);
}
}]);
很抱歉,我没有注意到代码中的更改。谢谢你的回答,我会检查它。非常感谢Gatsbill,你的init方法创造了奇迹:D。现在它工作了。是的,我没有考虑更改。现在它工作了谢谢;)我可以检查数组更改以通知新邮件吗!?这就是您使用的:'$scope.$on('gotnewmail!',function(event,args){$scope.mails=args.data;});'不知道你在问什么
app.factory('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){
var updatedData = [];
return {
init: init
}
function init() {
$interval(function(){
return $http.post('inc/get_mails.php?user='+'<?php echo $_SESSION['user']; ?>')
.success(function(response){
// check if their is a difference between this call and the last call
if (updatedData.length !== response.length) {
updatedData = response;
alert(updatedData);
$rootScope.$broadcast('got new mail!', { data: updatedData });
}
})
.error(function(err){console.log(err);});
},1000);
}
}]);
app.controller('yourCtrl', ['mails', '$scope', function(mails, $scope) {
mails.init();
// each time you have a new mail
$scope.$on('got new mail!', function(event, args) {
$scope.mails = args.data;
});
}]);