1

更新が必要な場合はサーバーからデータをフェッチするか、更新がない場合はキャッシュされた配列を返すAngular jsサービスを作成しようとしています。どちらの場合も、サービスは を返す必要がありpromiseます。サービスコード:

getLikesForMe = function() {
    var defer = $q.defer(), prom = defer.promise;

    if (angular.isUndefined(this.likesForMe) ||
        updateStatus.likesForMe === true) {
      var that = this;

      prom = $http.get(API_URL + 'likes-to.json')
        .then(function(result){
          updateStatus.likesForMe = false;
          that.likesForMe = result.data;
        });

    } else {
      defer.resolve(this.likesForMe);
    }

    return prom;
  }

現在のコントローラ コード:

MainUser.getLikesForMe().then(function(result) {
  $scope.likesList = result;
});

優先コントローラーコード:

$scope.likesList = MainUser.getLikesForMe();

しかし、現在getLikesForMe()は、最初の 2 番目の関数 ( ) 呼び出しの後にのみ機能します。リストは空で、「結果」変数はundefinedです。

私は遅延オブジェクトを初めて使用し、私の英語はかなり貧弱ですが、間違いがどこにあるかを理解していただければ幸いです。どうもありがとう!

4

2 に答える 2

3

You have 2 issues

  • On the first call, the promise you return will be resolved with undefined as you're not returning anything from the then success callback from your call to $http.get. If you return that.likesForMe from that callback, I suspect it will work as you expect. You should probably read up on chaining promises. (Shameless plug: I wrote a blog post on AngularJS promises which contains sections on chaining)

  • The code is quite complicated for what it does, and you almost-never have to create a promise via $q.defer() if all you're doing to working with existing promises. It usually makes things more complicated and harder to deal with errors. You can also use $q.when() to create a promise from a non-promise value. So I propose something like

    getLikesForMe = function() {
      var that = this;
      var useCache = !updateStatus.likesForMe && !angular.isUndefined(this.likesForMe);
    
      return useCache ? $q.when(that.likesForMe) : $http({
        method: 'GET',
        url: API_URL + 'likes-to.json'
       }).then(function(results) {
         updateStatus.likesForMe = false;
         that.likesForMe = results.data;
         return that.likesForMe;
       });
    });
    

You could also read up in the docs for $http cache to see if you could come up with a solution that uses it.

于 2014-05-03T17:19:33.493 に答える
0

新しいバージョンのコントローラー コードを使用する場合は、サービスから promise を返すことはできません。

http 呼び出しから戻ったときに拡張される空のオブジェクトを返すことができます。

$rootScope.$apply()次に、コントローラーに通知されるようにを発行する必要があります。

于 2014-05-03T15:33:03.800 に答える