始终从服务返回数据

时间:2016-02-24 14:05:27

标签: angularjs

我有一系列服务要么从API服务器获取数据,要么返回本地存储中存在的数据。

.factory('LogEntryResource', function(config, $resource) {
  return $resource(config.apiUrl + 'logentries/:id/');
})

.factory('LogEntry', function(localStorageService, LogEntryResource) {
  var localLogEntries = localStorageService.get("logEntries");

  return {
    all: function() {
      if(localLogEntries){
        return localStorageService.get("logEntries");
      } else {
        return LogEntry.query(function(data){
          localStorageService.set("logEntries", data);
          return data;
        });
      }
    },
    get: function(logEntryId){
      ...
    },
    delete: function(logEntryId){
      ...
    },
    update: function(logEntryId){
      ...
    }
  }
})

问题是在app控制器中有时会返回一个promise,有时会返回数据,所以我需要处理LogEntry.all()的返回值,要么等待promise的解析,要么使用数据

我不确定如何去做,因为我可以使用适用于承诺的.then(),但如果它有数据则未定义,反之亦然。我知道我做错了什么,并寻求建议如何处理这种处理数据或承诺返回的情况。

.controller('LogEntryCtrl', function($scope, LogEntry) {
  // var data = LogEntry.all();
  // var promise = LogEntry.all();

  $scope.logEntry = ???
}

我希望有一个很好的可重用解决方案,而不是每次在我的控制器/路由中使用此代码时都要检查它是什么

 // trying to avoid doing this
 var logEntry = LogEntry.all();

 if(logEntry.isPromise){
   // do promise stuff here
 } else if(logEntry.isData {
   // do data stuff here
 }

1 个答案:

答案 0 :(得分:2)

我的建议总是会回报一个承诺。您可以使用$q.resolve()为已解决的承诺创建快捷方式

.factory('LogEntry', function(localStorageService, LogEntry, $q) {
  var localLogEntries = localStorageService.get("logEntries");

  return {
    all: function() {
      if(localLogEntries){
        return $q.resolve(localLogEntries);
      } else {
        return LogEntry.query(function(data){
          localStorageService.set("logEntries", data);
          // update variable also
          localLogEntries = data;
          return localLogEntries ;
        });
      }
    },

在控制器中,您总是以这种方式使用then()

LogEntry.all().then(function(data){
   $scope.data = data;
});