Hi I am using angularJS to my project and I use $http function to retrieve some data. but i want to hold other statements from executing until $http finishes. Any suggestions?
Use .then() and place your rest of the codes there.
Ex:
$http(//your call here)
.then(function (contents) {
alert(JSON.stringify(contents));
});
Related
In angular JS 1.6 how to call the two functions simultaneously after we get the success response from service. Is it possible ?
Wrap both function within .success():
this.myPromise().success((response) => {
this.myFunctionOne(response);
this.myFunctionTwo(response);
})
This way, .success() will fire two functions.
But actually, I have no idea if this is what you were asking for..
I was taught that we use factories/services to eliminate the duplicate coding. Here's a part of the code which works fine.
app.controller('ServicesCtrl',['$scope','DataFactory',function($scope,$http,DataFactory){
DataFactory.GetData('services1.json')
.then(function(response){
$scope.returnedData = response.data;
})
.catch(function(response){
console.log('Error in process',response.status,response.data);
});
}]);
app.controller('ContactCtrl',['$scope','DataFactory', function($scope,DataFactory){
DataFactory.GetData('location.json')
.then(function(response){
$scope.returnedData = response.data;
})
.catch(function(response){
console.log('Error in process',response.status,response.data);
});
}]);
app.factory('DataFactory',['$http',function($http){
var factory = {};
factory.GetData = function(path) {
return $http.get(path);
}
return factory;
}]);
My question is 1. Why use services/factories to make such ajax calls when we have to work on the promises inside controllers? I mean, I have to make the same .then and .catch calls in both the controllers here. Where is the efficiency in it? Is there any better way to do this? Or am I doing this wrong? Is it possible to to work on those promises inside the factories and return the response.data to different controllers?
The thing here is re-usability of code . Now suppose you have a service called
angular.module('test')
.service('testService', function ($http) {
this.getBidsUser = function ($username) {
var endpoint = "bids/users/"+$username;
return $http({
method: 'get',
url: endpoint
});
};
}
which returns bids of a user . You might want to use the same information in different views. So its a good idea to use service so that you dont have to rewrite same code again .
Once more you might want to have all the same end point related service on the same service for maintainability .
You might need to change end points for a service which will be hectic if you do not use service pattern .
Promises arr call backs . If you process those promises inside a service it will not be easy to maintain caller timeline .
Hi we use factories and services
to make the application more modular,
to have the possibility to reuse the code,
to hide the implementation detail
For example a service which makes an http call it may be seen as an high level "service" which gives you back the required object, indipendently by the call type and it's reusable at high level.
The service allows to customize the call parameters, maybe avoiding that some of them are to be specified by the calling controller. Or it can do some preprocessing or post processing, it can do some caching and so on. And its portable, so you can call it each time you need.
For your last question
Is it possible to to work on those promises inside the factories and
return the response.data to different controllers?
Maybe it's possible, but may be complex to implement as it has to do with the timing of the response. Instead i suggest you the $resource service in the module ngResource, which can already do what you neeed.
See docs:
AngularJs Tutorial on $resource
Angularjs Programming guide on $resource
I am using Angular's $http for get, post, put and delete operations. Right now i have written this code in my Angular controller.
-- Now --
I want to use $resource instead of $http and want to place this data calls in a factory. After searching on so many websites i found this:
"use strict";
angular.module("app")
.factory('someFactoryName', function ($resource) {
return $resource('/foo/bar/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
}
});
})
Now i can use this factory in my controller like this:
$scope.entry = new someFactoryName();
$scope.entry.$save(function (response) {
//some code
});
Till here everything is fine.
-- Now what i want to achieve --
I have seen John Papa's Angular1 Style guide and i found this section, the code he demonstrated is very good i want to achieve the same thing i mean he called the ajax call and handled the response in the separate factory but here my case is little different. My only challenge is that he have used $http and i want to use $resource but for $resource i already have a factory then how can i write the response handling code in the same factory in which $resource is configured. I have 2 ideas in mind:
I can define one more factory and can inject this factory into new one,
Somehow write the code in this same factory
I don't know which one is best and how to achieve it, if you have any idea please help. Thanks.
I would suggest the first option.
Separation of concerns is important.
I've created a service that fetches through $http.get().
My service is used in a directive that renders to several ui elements. The service is async. It's used in the directive code like: myService.getStuff(), and it returns a customized promise (from within the callbacks of the $http.get promise).
But I want my service to only perform one call to $http.get during the lifecycle of the app. And cache the http.get response.
So say I use the directive 2 times in my html. Then this is what I want: The first time it's called it (returns immediately and) fetches stuff via $http.get. The second time it's called it detects an outstanding call to $http.get. thus does not do another call to $http.get, but somehow awaits the return of the first call.
You might want to use the internal cache of $http
return $http.get(/*...*/, { cache: true }).then(/*...*/);
or just cache the promise in your service.
function MyService($http) {
var promise;
this.get = function() {
promise = promise || $http.get(/*...*/).then(/*...*/);
return promise;
}
}
If you're using uirouter, another way is to resolve the data in a parent state, and inject the resolved data to all your components.
Set cache to true like this:
$http.get(yourUrl, {cache: true})
.then(...)
Any subsequent call to this will use the cached value.
Rather than running config at the initial stage, I would like to config something at a later stage based on some information fetched from server like this:
$http.get(url)
.success( function(response){
angular.module('MyApp').config(['$myServiceProvider', function( $myServiceProvider){
$myServiceProvider.enableSomething(true); // delayed !!!
}]);
});
However the running of the body of config() function is blocked until I loaded some lazy-loaded partial. Maybe a $compile() will trigger it.
I do not understand why it is like this and how to make the config() body invoked immediately.
Thanks.
The angular-deferred-bootstrap module does that exactly : https://github.com/philippd/angular-deferred-bootstrap
See : https://github.com/philippd/angular-deferred-bootstrap#attach-constants-to-specific-modules
Also, this question offers other options : AngularJS : Initialize service with asynchronous data
Would it be possible in your scenario to use $http in a module.run call and configure your service in the $http's success handler?
If it absolutely needs to happen before the module.configcall, remove ng-app from your HTML and do the bootstrapping yourself by calling angular.bootstrap as outlined in the documentation after you have fetched the file.
As far as I'm aware, there's no way of blocking the configuration phase.