Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何存储Pubnub历史记录中的数据并使其可供所有控制器使用?_Javascript_Angularjs_Pubnub - Fatal编程技术网

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);
});