i need to preload images after an $http service.
Now in my application i'm using promise/resolve method to preload data with service.
here my service:
angular.module('davelab.services', [])
.factory('srvProjects', ['$http', function ($http) {
var API = '/backend/api/';
var sdo = {
getProjects: function() {
var promise = $http({ method: 'GET', url: API + 'get_posts/' }).success(function(data, status, headers, config) {
return data;
});
return promise;
}
};
return sdo;
}]);
});
and here the route part:
$routeProvider.when('/projects', {
templateUrl: 'app/partials/list-projects.html',
controller: 'ProjectsCtrl',
resolve: {
projects: function(srvProjects) {
return srvProjects.getProjects();
}
}
});
it works well with data but for the images retrieved from api request it doesn't work.
How can I preload images in cache before show the view with this method?
i have to iterate through data into success callback or somewhere else?
thanks.
Take the URL's you're receiving from your original request, but instead of resolving the promise right away, create a new promise for each image. Preload the image using any method you prefer (but it needs a callback to resolve its promise) and resolve each promise after the image is loaded. You should end up with an array of image promises. and then return $q.all(imagePromises) from your resolve. Check out the docs for $q.
$q.all will return a promise that is only resolved when all promises passed into it are resolved.
I haven't tested it, but I think you might be able to just use $http on each image URL and it will cache it for you and give you a nice promise to pass into $q.all. So basically you'll have an array of $http calls.
You can use like this in your controller
$scope.preloader = true
then you can use angular promise of
.then(function(result){
//your code goes here
$scope.preloader = false;
}
Also you have $scope.preloader= false in you error block
If you have multiple Ajax calls at a same time parallely then use
$scope.preloader = 0;
on stating the request use
$scope.preloader++;
and when done use
$scope.preloader--;
You can have more clear answer here
Showing Spinner GIF during $http request in angular
Related
I have a service that (when it's all said and done) updates a value on the database.
I would like to update the view scope based on the result (success/fail) but of course the http request used by the service is asynchronous so the return value is not immediately available and comes up undefined in the controller.
If I were making the http request inside the controller, I would update the scope inside the callback function, but because Im using a service, the scope's umm... scope(?) is not available to it.
Im thinking a Promise is what I need to be returning but perhaps there is something more simple.
SERVICE
.service('doStuff',function($http){
this.update = function(data) {
$http.post('http://api.internet', data).then(function(res){
return(res.data.result);
});
}
})
CONTROLLLER
/* service is injected into controller etc. */
var result = doStuff.update(data);
p(result); // undefined (as expected)
I figured since Im returning from the http callback, it would wait for the result to be available before returning but I guess Im missing something.
Since $http is always async, you cannot return anything in the call back function. It is as good as not returning anything.
What you need to do is you need to return the $http promise, and then handle the callback functions in your controller.
Service:
.service('doStuff', function($http) {
this.update = function(data) {
return $http.post('http://api.internet', data);
}
})
Controller:
doStuff.update(data).then(function(result){
p(result);
});
Foremost, you need to return the query itself. Looks like
this.update = function(data) {
return $http.post('http://api.internet', data).then(function(res){
return(res.data.result);
});
}
Next step, you need get out of the promise function.
doStuff.update(data)
.then(function(res) {
//someone if request is success
})
.catch(function(rej) {
//someone if request is reject
});
In jquery when we fire ajax call ,when its successful,success function is called but, now in angular I have seen people using then as well as success.After googling a bit i found that then returns a promise.
If i want to load a route which has data that comes from a service I use resolve to execute http req before binding data into template but here in http I have used neither success/then.
My http request part :
movieserviceObj.getlist=function(){
return
$http({ url:'app/api/entertainment.php',data:$.param(dataString),method:'POST'});
Resolve part in config:
resolve:{movieslist:moviesController.getallMovies}
Controller :
var moviesController=app.controller('moviesController',function($scope,movieslist){
$scope.movies=movieslist.data.result
});
moviesController.getallMovies=function($q,$timeout,movieservice)
{
var defer=$q.defer();
$timeout(function(){
defer.resolve(movieservice.getlist());
},1000);
return defer.promise;
}
Now above code works completely fine but data-binding occurs after 1 sec as set in $timeout.My issue is that http request gets data within 1 sec, but then too I have to wait for 1sec.Is there any way,that as soon http req is completed it should return promise to resolve till then show loading bar ? Here in http i have not used success / then so how it works.Also even after successful http request how can I make sure that it has key named 'status' in response set to true, if true then only resolve or reject.
$http already returns a promise, so using then() makes much more sense here because:
you won't need to wait 1s every time
you won't risk not getting the data if the requests takes longer than 1s
Here's an example:
var moviesController = app.controller('moviesController',function($scope, movieservice){
movieservice.getlist().then(function(res){
$scope.movies = res.data;
}, function(err){
console.log('error:', err);
});
})
});
There are some nice point about the actual differences between then and success here: Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments.
Also even after successful http request how can I make sure that it has key named 'status' in response set to true, if true then only resolve or reject.
You'd have to modify your service to do that, similar to what you were doing in a controller:
movieserviceObj.getlist=function(){
var defer=$q.defer();
$http({
url:'app/api/entertainment.php',
data:$.param(dataString),
method:'POST'
}).then(function(res){
if (res.status === true) {
defer.resolve(res);
}
else {
defer.reject({error: 'Status not true'});
}
}, function(err) {
defer.reject(err);
})
return defer.promise;
}
Info about route resolve:
An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired.
The web service I am using returns my data in a format that must be modified before I can put it into my view.
Here is my basic factory:
.factory( 'myServices', function ( $http ){
var myServices = {
getInfo: function(){
var promise = $http(
{
url: "/deal-details.json",
method: "GET"
})
.then(function(response) {
return response.data;
}
);
// some logic to modify promise???
return promise;
}
};
return myServices;
});
The question I have is should I be doing any modifications to promise inside of getInfo() before returning promise? The previous developer was modifying the value returned from myServices.getInfo() in the controller but that doesn't seem right to me.
How about using the transformResponse that $http offers to you? Something like
$http({
method : 'GET',
url : "/deal-details.json",
transformResponse : function (response) {
// your modification here
return response.data;
}
});
It really just depends on what needs to be modified - or if it needs to be modified every time or not. If 100% of the time the data needs to be modified, may as well have it do it within the service.
If, however, different modifications will need to be done depending on which function is calling it - then it should probably be done within the controller.
#przno's answer is good if you need to intercept all $http requests. If all promises need to be modified, or validated in some way - then that is a great solution! But it seems like your question was in regard to a particular service.
I'm sure there is an easy way to do what I want, I just cant wrap my head around it. How can I get the http interceptor in angular to retry a request if it fails? I imagine I would have to build some sort of promise in the request right? Then in the response I would have to check whether the response was an error and if so, do the promise? How is that done? I have been trying to adapt the example here: http://docs.angularjs.org/api/ng.$http
The reason I am trying to use an interceptor is because I need to add the token and a few other things to the request url, as well as some things to handle xdr's.
Here's a $http interceptor that (immediately) replays timed out request(s) (i.e. response status 0). There were two non-obvious (to me!) elements to constructing this example:
How to call $http from within the interceptor - simply adding $http to the dependency list didn't work as angular complains of a circular dependency
How to reference the original request from the response object in order to retry it
This answer addresses both topics but is more involved so I include a simplified version below.
joinApp.factory('httpResponseErrorInterceptor',function($q, $injector) {
return {
'responseError': function(response) {
if (response.status === 0) {
// should retry
var $http = $injector.get('$http');
return $http(response.config);
}
// give up
return $q.reject(response);
}
};
});
joinApp.config(function($httpProvider) {
$httpProvider.interceptors.push('httpResponseErrorInterceptor');
});
In your actual implementation, you would likely want more sophisticated http response code processing, a limit to the number of times you retry, etc.
For the sake of completeness, here is a version of mygzi's answer with retry delay:
.factory('httpResponseErrorInterceptor', ['$injector', '$q', '$timeout', function($injector, $q, $timeout) {
return {
'responseError': function(response) {
if (response.status === 0) {
return $timeout(function() {
var $http = $injector.get('$http');
return $http(response.config);
}, 15000);
}
return $q.reject(response);
}
};
}])
.config(function($httpProvider) {
$httpProvider.interceptors.push('httpResponseErrorInterceptor');
});
$timeout returns a promise that is completed with what is returned from the function parameter, so we can conveniently just return the $http call wrapped in $timeout.
I've done this for an app I wrote before. To do the retry wrap the $http usage in a function (or preferably in a service so that you can reuse it easily). If the request fails, call the function again.
The trick is then to pass the promise object along with each request. If you create a new promise with each request then it won't match the one you returned to the original caller, so the original caller won't get his promise resolve once the request passes.
So it is something like this (note that the defer object is passed along in each retry):
app.service('HttpService', ['$q', function($q) {
this.makeRequest = _makeRequest;
function _makeRequest(url, data, deffered) {
// We want to keep the same promise for each request, so we don't loose track
if (deferred === undefined) {
deferred = $q.defer();
}
// Now make the request
$http({...}).success(...).error(
function(){
// If some condition
_makeRequest(url, data, deffered);
}
)
// Lastly return the promise
return deferred.promise;
}
}])
There is related question about processing $http in a service, but I wanted to elaborate slightly. I would like my controller to be able to execute service calls using API similar to the Angular $http API:
$scope.login = function(user) {
securityService.login(user).success(function(data) {
$scope.data = data;
}).error(function(data) {
$scope.error = data;
});
};
That's a nice readable API. On the surface, all I would need to do in the service API is:
return {
name : 'User Service',
login : function(user) {
return $http.post("/api/login", user);
}
};
Great, it returns the promise and the success and error messages come with. But... What if I want to deal with the success and failure cases in the service? I want to maintain the nice, readable service API. In this case, maybe I'd want to preserve the user so that I could expose methods like securityService.currentUser() or `securityService.isLoggedIn()'.
I tried the $http.post().then(...) promise API, but those return the entire HTTP response. Again, I want to isolate HTTP to the services and maintain a similar concrete callback API.
You could make your own promise in login using angular's $q:
var deferred = $q.defer(),
promise = deferred.promise;
$http.post("/api/login", user).success(...).error(...)
return promise;
Within the success/failure of the $http promise in your service, resolve/reject your deferred object.
Edit:
Expanding upon the $http.post:
$http.post("/api/login", user).success(function(data) {
if (data == "foo") { // success case?
deferred.resolve('you logged in!');
} else {
deferred.reject('something really bad happened!');
}
})
I just ran a test case and it seems that if I return the promise from the service API like this:
return $http.post("/api/login", user).success(...).error(...)
I can also do the same in the controller:
service.login(user).success(...).error(...)
and both get called, the service first and the controller second. That's perfect!