2016-09-10 3 views
2

に角度サービスからオブジェクトを返すために、どのように持って、次のサービス、私は私が使用できるように、私のコントローラでvObjectsを取得したいと思いコントローラ

.service('indexDBService', function ($indexedDB, firebaseService) { 
    var objects = []; 
    var addToVideos = []; 
    var _this = this; 

    firebaseService.getvideosApi().then(function(response){ 
      _this.videos = response.data; 
      var userVideos = _this.videos; 
      for (var key in userVideos) { 
      if (userVideos.hasOwnProperty(key)) { 
       var video = {"file_id": userVideos[key].file_id, "filename": userVideos[key].filename, "file_status": userVideos[key].file_status, "user_id": userVideos[key].user_id, "video_avatar": userVideos[key].video_avatar, "upload_date": userVideos[key].upload_date, "file_dislikes": userVideos[key].file_dislikes, "file_likes": userVideos[key].file_likes, "downloadUrl": userVideos[key].downloadUrl} 
      addToVideos.push(video); 
      } 
      } 
      if((objects.length) < (Object.keys(_this.videos).length)){ 

      $indexedDB.openStore('userVideos', function(store){ 
       store.upsert(addToVideos).then(function(e){ 
       // do something 
       }); 
      }); 

      } 
     }); 
     //get indexDB Videos 
     $indexedDB.openStore('userVideos', function(store){ 
      store.getAll().then(function(userVideos) { 
      objects = userVideos; 
      _this.vObjects = objects; 
      }); 
     }); 
     }); 

。どのようにして_this.vObjectsを私のコントローラに戻すか、それとも通過するのですか?

答えて

1

これは角度のあるサービスなので、約束事で作業する必要があります。プロミスでは、非同期データにアクセスし、firebaseおよびinddxdbサービスでそれらを使用しています。私は_this.vobjectを使ってサービス内のデータをキャッシュしていると仮定し、毎回リクエストを行う必要はありません。私はこのようなあなたのサービスに$ qを注入するでしょう。

. service('indexDBService',function($indexedDB, firebaseService,$q) 

$ qは約束を構築するためのAPIです。角度サービスでは、メソッドをこれに追加して公開します。あなたのデータを取得するためのメソッドを作成するには、このように構築します。

this.getVobj = function(){ 

    var deferred = $q.defer() 

    if(_this.vObjects){ 
     deferred.resolve(_this.vObjects); 
    } else { 

$indexedDB.openStore('userVideos', function(store){ 
     store.getAll().then(function(userVideos) { 
     objects = userVideos; 
     _this.vObjects = objects; 
     deferred.resolve(objects); 
     }); 
    }); 
} 

    return deferred.promise; 

}; 

次に、あなたのコントローラに入れてサービスを注入します。

myModule.controller('myCtrl', function(indexDBService){ 
      indexDBService.getVobj().then(function(vObj){ 
       //Do stuff with vobj 
      }); 
});