Angularjs 始终从服务返回数据

Angularjs 始终从服务返回数据,angularjs,Angularjs,我有一系列的服务,要么从API服务器获取数据,要么返回本地存储中的数据 .factory('LogEntryResource', function(config, $resource) { return $resource(config.apiUrl + 'logentries/:id/'); }) .factory('LogEntry', function(localStorageService, LogEntryResource) { var localLogEntries = l

我有一系列的服务,要么从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 Controller中,有时会返回承诺,有时会返回数据,因此我需要处理
LogEntry.all()的返回值,以等待承诺解析或使用数据

我真的不知道该怎么做,因为我可以使用一个
.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
 }

我的建议是永远回报一个承诺。您可以使用
$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;
});

我的建议是永远回报一个承诺。您可以使用
$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;
});

您是否尝试过.then(函数(数据){});要解决承诺?您是否尝试过.then(函数(数据){});要解决承诺?请同意@charlietfl$q是解决你问题的好方法,同意@charlietfl$q是解决你问题的好办法