This question already has answers here:
Immediately return a resolved promise using AngularJS
(5 answers)
Closed 7 years ago.
I have a problem with a promise. This is the controller for a detail page. I want to get the item details from a web service (or from the local store if they are stored).
app.controller('ProductCtrl', function($scope, productsService) {
//load the product by id from productService
productsService.get("CODE-1111").then(function(result){
$scope.currProduct = result;
$scope.currProductSizes = $scope.currProduct.sizes;
});
}
app.service('productsService', function($http, localStorageService){
var _key = 'myProducts'
var _storedData = []
var self = this;
self.get = function(id){
var i = 0;
return self.getAll().then(function(result) {
//get the item by id
_storedData = result;
for(i=0;i<_storedData.length;i++){
if(_storedData[i].id == id)
break;
}
return _storedData[i];
});
}
self.getAll = function() {
_storedData = localStorageService.get(_key);
if(_storedData != null){
**//How return a promise here? Or how I can handle it**
return _storedData instanceof Array ? _storedData : [_storedData];
}
else{
var url = baseUrl + "api/GetStyles";
return $http({method: 'GET', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }})
.then(function(response) {
_storedData = mapToProducts(JSON.parse(response.data));
return _storedData;
},
function(response) {
console.log(response.status);
});
}
};
})
The first time (the items aren't in the local store) all works well because the getAll method return a promise, but the second time it doesn't return a promice so I get
Cannot read property 'then' of undefined
How I can solve this?
You can return a promise like this:
return $q.when(_storedData instanceof Array ? _storedData : [_storedData]);
You need to response a promise in your get and getAll functions, I changed your functions to do that:
app.service('productsService', ['$http', '$q', 'localStorageService', function($http, $q, localStorageService){
var q = $q;
var _key = 'myProducts';
var _storedData = [];
var self = this;
self.get = function(id){
var deferred = q.defer(); //Initialize your own promise
var i = 0;
self.getAll().then(function(result) {
//get the item by id
_storedData = result;
for(i=0;i<_storedData.length;i++){
if(_storedData[i].id == id)
break;
}
return deferred.resolve(_storedData[i]); //This is your response for success
}).catch(function(error) {
deferred.reject(error); //This is your response for failure
});
return deferred.promise; //return the promise
}
self.getAll = function() {
var deferred = q.defer(); //Initialize your own promise
_storedData = localStorageService.get(_key);
if(_storedData != null){
var data = _storedData instanceof Array ? _storedData : [_storedData];
deferred.resolve(data);
} else {
var url = baseUrl + "api/GetStyles";
$http({method: 'GET', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }}).then(function(response) {
_storedData = mapToProducts(JSON.parse(response.data));
deferred.resolve(_storedData); //This is your response for success
}, function(error) {
deferred.reject(error); //This is your response for failure
});
}
return deferred.promise;
};
}]);
Related
I have this factory which is called multiple times by directives. Since it returns a lot of data the rendering at the end is slow. How can i call it only once or save it in a cashe when its called the second time and n time?
appBMdata.factory('Trends',['$http','Config','$q',
function($http,Config,$q){
function getAllData() {
var source1 = $http.get(Config.api_server + 'bizmonitor/indicators/get/2016');
var source2 = $http.post(Config.api_server + 'trends');
return $q.all([source1, source2]);
};
return {
getAllData : getAllData,
};
}]);
You can save the promise in a var, and return it if it has been already set:
appBMdata.factory('Trends',['$http','Config','$q',
function($http,Config,$q){
var _cacheGetAllData;
function getAllData() {
var source1 = $http.get(Config.api_server + 'bizmonitor/indicators/get/2016');
var source2 = $http.post(Config.api_server + 'trends');
_cacheGetAllData = _cacheGetAllData || $q.all([source1, source2]);
return _cacheGetAllData;
}
return {
getAllData : getAllData,
};
}]);
If you want successive calls to force to update, you can edit it to something like this:
appBMdata.factory('Trends',['$http','Config','$q',
function($http,Config,$q){
var _cacheGetAllData;
function getAllData(ignoreCache) {
var source1 = $http.get(Config.api_server + 'bizmonitor/indicators/get/2016');
var source2 = $http.post(Config.api_server + 'trends');
if (ignoreCache) {_cacheGetAllData = undefined;}
_cacheGetAllData = _cacheGetAllData || $q.all([source1, source2]);
return _cacheGetAllData;
}
return {
getAllData : getAllData,
};
}]);
I'm resolving it in the service and then store data, if it has data, returning data in a promise. If you want to fetch data again just add true as first arguement.
appBMdata.factory('Trends', ['$http', 'Config', '$q', function($http, Config, $q) {
var data;
function getAllData(nocache) {
var deferred = $q.defer();
if (data.length && !nocache) {
deferred.resolve(data);
} else {
var source1 = $http.get(Config.api_server + 'bizmonitor/indicators/get/2016');
var source2 = $http.post(Config.api_server + 'trends');
$q.all([source1, source2])
.then(function (values) {
data = values;
deferred.resolve(data);
})
.catch(function (err) {
deferred.reject(err);
});
}
return deferred.promise;
}
return {
getAllData : getAllData
};
}]);
Yes you can keep the data on $rootScope and return the data from there when its called multiple times.
appBMdata.factory('Trends',['$http','Config','$q','$rootScope'
function($http,Config,$q,$rootScope){
function getAllData() {
var source1 = $http.get(Config.api_server + 'bizmonitor/indicators/get/2016');
var source2 = $http.post(Config.api_server + 'trends');
return $q.all([source1, source2]);
};
if($rootScope.data){ // check if data already present
$rootScope.data=getAllData(); // assign data to rootscope
}
return {
getAllData : $rootScope.data, //return data from rootscope
};
}]);
How to pass data from promise then method to an object method.
this.httpReq(url).then(function (data) {
this.storeData(data);
});
I know that here I'm out of scope and this doesn't refer to my object. But, nevertheless, I can't understand how to resolve it.
Bellow you can find entire code snippet. In the end, I want to get data from the service API and store it in the object array property this.storage.
var http = require('http');
function CoubApi (url) {
this.url = url;
this.storage = [];
this.httpReq = httpReq;
this.searchData = searchData;
this.storeData = storeData;
}
function httpReq (url) {
var promise = new Promise (function (resolve, reject) {
http.get(url, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
if(data.length > 0) {
resolve(JSON.parse(data));
} else {
reject("Error: HTTP request rejected!");
}
});
}).on('error', function (err) {
console.log("Error: ", e);
});
});
return promise;
}
function storeData (data) {
var i;
console.log("Storrrreee");
for(i = 0; i < 10; i++) {
this.storage.push(data.coubs[i]);
}
}
function searchData (searchtext, order, page) {
var url = this.url+
"search?q="+searchtext+
"&order_by="+order+
"&page="+page;
this.httpReq(url).then(function (data) {
this.storeData(data);
});
}
var coub = new CoubApi("http://coub.com/api/v2/");
coub.searchData("cat", "newest_popular", 1);
console.log(coub.storage);
You can store this in varaible:
var self = this;
this.httpReq(url).then(function (data) {
self.storeData(data);
});
or use bind:
this.httpReq(url).then(function (data) {
this.storeData(data);
}.bind(this));
I am recovering all data in allEnquetes. I just find the requested this list, but an error occurs because the allEnquetes returns a promise.
.factory('enquetesAPI', function($http,myConfig){
return {
allEnquete: function(){
return $http.get(myConfig.remote + '/lists.asp?acao=list-enquete&codadmin='+myConfig.codadmin);
},
getEnquete: function(enqueteId) {
for (var i = 0; i < this.allEnquete().length; i++) {
if (this.allEnquete()[i].codigo === parseInt(enqueteId)) {
return this.allEnquete()[i];
}
}
return this.allEnquete()
}
};
})
This is the result when I console.log ( this.allEnquete )
allEnquetes returns a promise so you just can't loop through that. Check below code. I have not tested it. but this should give you some idea on how you should ideally be doing this.
.factory('enquetesAPI', function($http, $q, myConfig){
return {
allEnquete: function(){
console.log('called');
return $http.get(myConfig.remote + '/lists.asp?acao=list-enquete&codadmin='+myConfig.codadmin);
},
getEnquete: function(enqueteId) {
var deferred = $q.defer();
this.allEnquete().then(function(enquetes){
var returnVal = enquetes;
for (var i = 0; i < enquetes.length; i++) {
if (this.allEnquete()[i].codigo === parseInt(enqueteId)){
returnVal = enquetes[i];
}
}
deferred.resolve(returnVal);
}, function(errorResponse){
deferred.reject(errorResponse);
});
return deferred.promise;
}
};
});
and this is how you should be using your service.
enquetesAPI.getEnquete(id).then(enquetes){
// do whatever you need to do
}
I have an array of tags which may contain up to 3 items.
Next I pass tags into my getTagQuotes function and am trying to set a promise variable to it. Right now I'm getting promise is undefined.
// If there are tags, the wait for promise here:
if (tags.length > 0) {
var promise = getTagQuotes(tags).then(function() {
console.log('promise =',promise);
for (var i=0; i<tweetArrayObjsContainer.length; i++) {
chartObj.chartData.push(tweetArrayObjsContainer[i]);
}
chartDirective = ScopeFactory.getScope('chart');
chartDirective.nvd3.drawChart(chartObj.chartData);
});
}
else {
chartDirective = ScopeFactory.getScope('chart');
chartDirective.nvd3.drawChart(chartObj.chartData);
}
^ The goal above is to make sure that arrays in tweetArrayObjsContainer have been filled and pushed into chartObj.chartData before I draw my nvd3 chart.
Below is my getTagQuotes function which does another loop through the tags (up to 3) and calls another service GetTweetVolFactory.returnTweetVol which makes the actual API call to retrieve data.
I have code which checks if the we're on the final loop step, then calls the formatTagData function.
Inside formatTagData is where I fill the tweetArrayObjsContainer.
// Check for and GET tag data:
////////////////////////////////////////////////////////////////////
function getTagQuotes(tags) {
console.log('getTagQuotes called with',tags);
var deferred = $q.defer(); // <- setting $q.defer here
var url = 'app/api/social/twitter/volume/';
for (var i=0; i<tags.length; i++) {
var loopStep = i;
rawTagData = [];
GetTweetVolFactory.returnTweetVol(url+tags[i].term_id)
.success(function(data, status, headers, config) {
rawTagData.push(data);
if (loopStep === (rawTagData.length - 1)) {
// formatTagData fills the tweetArrayObjsContainer with data:
formatTagData(rawTagData);
deferred.resolve(); // <-- last step, so resolve
return deferred.promise;
}
})
.error(function(data, status) {
return 'error in returning tweet data';
});
}
function formatTagData(rawData) {
tweetArrayObjsContainer = [];
for (var i=0; i<rawData.length; i++) {
var data_array = [];
var loopNum = i;
_(rawData[i].frequency_counts).reverse().value();
for (var j=0; j<rawData[loopNum].frequency_counts.length; j++) {
var data_obj = {};
rawData[loopNum].frequency_counts[j].start_epoch = addZeroes(rawData[loopNum].frequency_counts[j].start_epoch);
data_obj.x = rawData[loopNum].frequency_counts[j].start_epoch;
data_obj.y = rawData[loopNum].frequency_counts[j].tweets;
data_array.push(data_obj);
}
var tweetArrayObj = {
"key" : "Quantity"+(i+1),
"type" : "area",
"yAxis" : 1,
"color" : tagColorArray[i],
"values" : data_array
};
tweetArrayObjsContainer.push(tweetArrayObj);
}
}
}
Your getTagQuotes function should return a promise with the $q service, check it out.
It should look like this:
function getTagQuotes(tags) {
var deferred = $q.defer();
(...)
// When the action is finished here, call resolve:
deferred.resolve();
(...)
// And in the end, return the promise
return deferred.promise;
}
And finally, in your main code, you'll do:
var promise = getTagQuotes(tags).then(function(){
console.log('promise =',promise);
// Fill chartObj with tweet data arrays
(...)
});
This function has no return statement.
function getTagQuotes(tags)
I’m really struggling to write a complex function in Angular that depends on promises. This is my first time writing a promise and I'm still not sure I fully understand how to do what I want to do with my code.
I have a variable var query = searchQuery.getQuery() in a controller ProfileNavCtrl. Then in my searchQuery service, getQuery fetches the value of localStorage.getItem('searchQuery') and checks if it’s an empty string or null. If it’s not empty or null, it simply returns the value to the controller. The value should be an array of slugs like ['foo','foo-bar','foo-bar-baz'].
If it is null or empty, it executes an $http.get call to fetch a JSON object and parse it. This is where things break down for me. I need getQuery() to return the value from $http.get (if the initial value of query is null) so that the controller variable query is assigned that value. As it is now, query (in the controller) is always set to null or undefined.
The $http.get call also calls setQuery() so that the query is persisted and future calls are avoided.
Here is my controller:
app.controller('ProfileNavCtrl', ['$scope', '$http', '$location', '$q', 'searchQuery',
function($scope, $http, $location, $q, searchQuery){
var query = searchQuery.getQuery;
// do something with query
And here is my service:
app.service('searchQuery', ['$http', '$timeout', '$q', function($http, $timeout, $q){
var query = [];
this.getQuery = new Promise(function(){
var query = localStorage.getItem('searchQuery');
if(query == "" || query == [""] || query == null){
var slugArray = [];
var query = $http.get('/companies.json')
.then(function(resp) {
if(resp && resp.data) {
for(var i in resp.data) {
var result = resp.data[i];
if(resp.data[i].name){
slugArray.push(resp.data[i].name.toLowerCase().split(' ').join('-'));
}
}
setQuery(slugArray);
} else {
resetQuery();
}
}, function(err) {
resetQuery();
}).then(function(resp){
return resp;
})
return query;
} else {
return query;
};
}).then(function(success){
return success;
});
UPDATE: 2nd Attempt
Here is my controller code:
var getQuery = searchQuery.getQuery();
getQuery.then(function(query){
query = searchQuery.getQuery();
// Check if user is on main site or portal
if(location.pathname.split('/')[3] == null){
var currentProfile = location.pathname.split('/')[1];
} else {
var currentProfile = location.pathname.split('/')[3];
};
// Get the next/prev query element (if any)
console.log('6: ');
console.log(query);
var prev = query.slice(query.indexOf(currentProfile)-1)[0];
var next = query.slice(query.indexOf(currentProfile)+1)[0];
// Check if next/prev is undefined and if so, set to first/last element in query array
if(prev){
var prevProfile = prev;
} else {
var prevProfile = query.pop();
};
if(next){
var nextProfile = next;
} else {
var nextProfile = query[0];
};
$scope.goToPrev = function() {
// Check if user is on main site or portal
if(location.pathname.split('/')[3] == null){
var profileUrl = location.origin + '/' + prevProfile;
// window.location = profileUrl;
console.log(profileUrl);
} else {
var profileUrl = location.origin + '/' + location.pathname.split('/').slice(1,3).join('/') + '/' + prevProfile;
// window.location = profileUrl;
console.log(profileUrl);
}
};
$scope.goToNext = function() {
// Check if user is on main site or portal
if(location.pathname.split('/')[3] == null){
var profileUrl = location.origin + '/' + nextProfile;
// window.location = profileUrl;
console.log(profileUrl);
} else {
var profileUrl = location.origin + '/' + location.pathname.split('/').slice(1,3).join('/') + '/' + nextProfile;
// window.location = profileUrl;
console.log(profileUrl);
}
};
});
Here is my updated service:
this.getQuery = function(){
return new Promise(function(){
var query = localStorage.getItem('searchQuery');
if(query == "" || query == [""] || query == null){
var slugArray = [];
return $http.get('/companies.json')
.then(function(resp) {
if(resp && resp.data) {
for(var i in resp.data) {
var result = resp.data[i];
if(resp.data[i].name){
slugArray.push(resp.data[i].name.toLowerCase().split(' ').join('-'));
}
}
setQuery(slugArray);
} else {
resetQuery();
}
return slugArray;
}, function(err) {
resetQuery();
});
} else {
return query;
};
});
};
In Angular promises are provided through the $q service. See the documentation for more detail.
The basic outline to implement $q promise in your service is outlined below, I'll leave the detail on how to save to local storage etc to you:
this.getQuery = function(){
var deferred = $q.defer();
var query = localStorage.getItem('searchQuery');
if(query == "" || query == [""] || query == null){
$http.get('yoururl').then(function(resp) {
// assuming resp is an array, else do your parsing to get array
query = resp;
deferred.resolve(query);
}, function(err) {
query = null;
deferred.reject(err);
});
} else {
deferred.resolve(query);
};
return deferred.promise;
};
You can then use this in your controller like:
var query = null;
searchQuery.getQuery().then(function(result) {
query = result;
}, function(err) {
// Error occured
});