Javascript 如何存储Pubnub历史记录中的数据并使其可供所有控制器使用?
我试图从Javascript 如何存储Pubnub历史记录中的数据并使其可供所有控制器使用?,javascript,angularjs,pubnub,Javascript,Angularjs,Pubnub,我试图从publinub.history()获取历史数据,存储该数据并使用不同的控制器更新视图 我已尝试创建一个服务: (function(){ 'use strict'; angular.module('app') .service('pubnubService', ['Pubnub', pubnubService ]); function pubnubService(Pubnub){ var history; Pub
publinub.history()
获取历史数据,存储该数据并使用不同的控制器更新视图
我已尝试创建一个服务:
(function(){
'use strict';
angular.module('app')
.service('pubnubService', ['Pubnub',
pubnubService
]);
function pubnubService(Pubnub){
var history;
Pubnub.history({
channel : 'ParkFriend',
limit : 1,
callback : function(historyData) {
console.log("callback called");
history = historyData;
}
});
return {
getHistory : function() {
console.log("return from getHistory called");
return history;
}
};
}
})();
问题是,
getHistory()
返回publinub.history()
之前的数据。在返回之前,我需要确保历史数据存储在history
上。由于publinub.history
是异步的,因此getHistory
函数也必须是异步函数
请尝试以下操作:
function pubnubService(Pubnub) {
return {
getHistory: function(cb) { // cb is a callback function
Pubnub.history({
channel: 'ParkFriend',
limit: 1,
callback: function(historyData) {
console.log("callback called");
cb(historyData);
}
});
}
};
}
若要使用此服务,您不能将其用作同步函数(例如,像var history=Pubnub.getHistory()
),您需要将函数作为参数传递,以充当回调函数
正确用法:
Pubnub.getHistory(function(history) { // here you have defined an anonym func as callback
console.log(history);
});