如何存储来自 Pubnub 历史的数据并使其对所有控制器可用?

How to store data from Pubnub history and make it available to all controllers?

我正在尝试从 Pubnub.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() returns Pubnub.history() 之前的数据。在返回之前,我需要确保历史数据存储在 history 上。

因为 Pubnub.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);
});