Reputation: 2902
I have the following service,
.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;
});
});
});
I would like to get the vObjects in my controllers so I can use there. How do I return or past the _this.vObjects to my controllers?
Upvotes: 2
Views: 1155
Reputation: 503
Since this is an angular service you should be working with promises. Promises allow you to access asynchronous data, you are using them with firebase and inddxdb services. Im going to assume you are using _this.vobject to cache the data in the service so you don't need to make the request each time. I would inject $q into your service like this
. service('indexDBService',function($indexedDB, firebaseService,$q)
$q is an API that allows you to construct promises. In an angular service you expose methods by adding them to this. In order to create a method to get your data you would construct it like this.
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;
};
Then to get it in your controller you inject your service.
myModule.controller('myCtrl', function(indexDBService){
indexDBService.getVobj().then(function(vObj){
//Do stuff with vobj
});
});
Upvotes: 1