Angular wait for a $http call to execute the next function - angularjs

I had been searching for this same issue here, I found something but all that seems to not be working for me. Let me describe my scenario:
I am adding some features to a Web app done by myself, that Web app is used to manage the developing of the webpage of some customers. Each customer has a webpage and for each customer there are a list of proposals webpages and who of the designers did that proposal, fine.
The list of the developers and be able to see who did what is the new thing in the Web app and the reason of my question, so, the problem is:
Once the web app loads I get the list of developers from the DB and a list of all the customers that have a webpage. So, the next thing the web app does is auto-select the first customer of the list and show its proposals in another list. To do that, the list of the developers is needed, but as it hasnt been still loaded I get the:
Cannot read property '0' of undefined
When I want to iterate over the $scope.developers object
What I do to get the developers is a $http call like this:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
$scope.developers = data;
});
I know $http performs async calls, but i need something that waits until the $scope.developers has the data loaded.
The problem comes when I need to use the data supposedly stored in $scope.developers but obvously its not. I tried to call the function that uses the $scope.developers inside the .success function but the same happens.
I tried to use the solution in this thread but I get the same error.
How to wait till the response comes from the $http request, in angularjs?
Any help ?? If something in my question is not clear I will try to explain it better.

Please just define $scope.developers as empty array before $http call ie
app.controller("someCtrl", function($scope, $http) {
$scope.developers = [];
//....
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
$scope.developers = data;
});
//..
});

Related

I am uploading the image file in Angular Js to call the java api but my form data is not hitting the api

controller:
$scope.fileToUpload = function(input) {
if (input.files && input.files[0]) {
CommonService.uploadContactImage.upload({
fileName : input.files[0].name
}, input.files[0], function(data) {
});
}
}
Service:
uploadContactImage:function(input){
console.log("game image");
var req = $http({method: 'POST', url: options.api.base_url + '/gameimageupload/',
dataType: 'json', headers: {'Content-Type': undefined}})
.success(function (data)
{
console.log("data" + data);
return data;
});
If you take a good look at your code you will see that there are quite a few things wrong with it. For example, you have defined in your service an uploadContactImage function which takes a single Javascript object as argument (input), while in your controller you attempt to call CommonService.uploadContactImage.upload(...) instead of CommonService.uploadContactImage(...). Additionally, even if the uploadContactImage function was called correctly it doesn't actually do anything with its argument, ie. the input object is never used in the function body.
These issues aside you cannot submit a file to the server just by adding it to the body of a POST request the way you (seem to be) trying to do. Without going into too much detail here, in order to upload a file from the browser a request with content type multipart/form-data needs to be submitted, which will contain your file as well as the necessary HTTP headers for the server to identify it and parse it correctly. I suppose you could try and construct this request yourself, however it's not a task for the faint-hearted. What I would suggest instead is to use one of the many file upload modules available for Angular.js. A Google search will give you quite a few modules that you can check out to see which better fits your needs.

AngularJS load data from server

I have the following scenario, a page that will show different widgets with different data, the back-end is ASp.NET Web API 2 with SQL Server and EF + Repository Pattern + Unit Of Work.
If I have to show quite some data, including user profile and other information on top of the widgets information, what will you recommend:
make one big $http.get request that will return a big json and bind that one to the UI
or
each controller (service) when it loads will make it's unique call to back-end and get's the data it needs to display, that means each widget will make a call to back-end and retrieve it's values.
I just want to know what do you recommend as a best practice.
IMHO the best way is to separate every request into single service methods that way you can reuse just a part of it and not make server calls to load to whole data, check the angular-resource $resource to have a clean reusable service of server calls and not a bunch of $https arround your code:
example:
A service that points some url of your backend server
.factory('ClientService', ['$resource', function($resource){
return $resource('http://some_url/:controller/:method', null, {
"agents": { method: 'GET', params: { controller: 'agent', method: 'search' }, cache: false },
"query": { method: 'GET', params: { controller: 'client', method: 'search' }, cache: false },
"save": { method: 'POST', params: { controller: 'client', method: 'save' } },
"delete": { method: 'POST', params: { controller: 'client', method: 'delete' } }
})
}])
The use in the controller (Injecting ClientService as dependency)
// If i want to query the agents into a scope element
// that will call the url = http://some_url/agent/search
$scope.agents = ClientService.agents();
// If i want to query a single client i cant send adtional params
// as is a get request it will call http://some_url/client/search?id=5
$scope.client = ClientService.query({id:5});
// and you can event manage callbacks if you want to
// This will send the client object to the url = http://some_url/client/save
ClientService.save($scope.client).$promise.then(function(response){ alert(response) })
As you can see this way you can access just the things you need from the backend server not having to do all the callback response if you dont need to and in a reusable cleaner way
Info Angular Resource Docs
I think it depends...
If performance might be a problem you should think about what is best for your User... Will the overhead of making 4 HTTP requests affect the user experience in anyway? Also, would a one big request take too much time to retrieve info from the database?
However if you want just to use a developer perspective of the problem, I'd prefer doing 1 generic API call then calling it 4 times in Angular with different parameters for each Widget.
It is likely that making 4 requests will actually be faster. Not to mention the data can start being populated on the screen as it comes back, instead of needing to wait for the slowest service.
For the max number of concurrent AJAX requehttp://www.coderanch.com/t/631345/blogs/Maximum-concurrent-connection-domain-browsers

How works simple table load with AngularJS?

I'm trying to learn AngularJS starting with that example: http://jsfiddle.net/mjaric/pJ5BR/
but when I tried to download in localhost, not works. I think that is a URL problem in /echo/json':
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
But I don't know how to solve it. Any idea or hint?
My finally idea is load json from a search petition. It's possible that 'data' will be charged from web or online.
The url: '/echo/json/' is a feature of JsFiddle. If you look at the tabs to the left, in Ajax Requests you can see the usage. It probably won't work with this url in localhost.
You need to create a web project, where you can send your request. You could send some search parameters from client side, then filter the data with those parameters in the server and then return the filtered data to show.
The following article will give you some good ideas
http://tutorials.jenkov.com/angularjs/ajax.html
This link provides a hands on example by a really good tutor.
http://weblogs.asp.net/dwahlin/learning-angularjs-by-example-the-customer-manager-application

Can I use $http to get a javascript for my web page?

I am using the following code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
Can someone advise me if it is possible to get a javascript with $http and show me how I can do it inside a function that returns a promise when it is completed. The reason I would like to use $http is that along with the request for the js I need to send a custom header for authorization.
Please note that this question is different from the one suggested as a duplicate in that I am also wanting to find out if I can get a javascript and add it to the page DOM in the same way as it was done with the .setRequestHeader. Thanks
Since $http is a implementation for XMLHttpRequest in Angular, you can of course make requests to get the contents of a JS file.
You can set additional headers with $http like this:
$http({
method: 'get',
url: 'some/js/file.js',
headers: {
"X-Custom-header": "foo"
}
}).then(function (data) {
// do something with the DOM here
});
So as you can see, you are actually able to do that.

AngularJS TypeError: Cannot read property 'protocol' of undefined

I have changed the $http > URL parameter inside my AngularJS app from
$http({ method:'POST',
url:'http://localhost/api/clients.php'
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
to
$http({ method:'POST',
url: ConfigService.Urls.Clients
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
where ConfigService is as follows:
Urls: {},
loadUrls: function(){
Urls.Clients = 'http://localhost/api/clients.php';
}
Of course I call loadUrls before loading controller through .Resolve so I am 100% sure Urls.Clients is not null.
After I did this change I started getting error:
TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (http://localhost/myapp/app/lib/angular/angular.js:13710:17)
at $http (http://localhost/myapp/app/lib/angular/angular.js:7508:23)
What is so confusing is that the application works just fine, except for that error I am getting...can someone please tell me what I am doing wrong here? and why I am getting this error if the application is already working without a problem.
This is clearly an issue with order. The loadUrls isn't getting called until after the $http call is run for the first time. This could be because controllers aren't necessarily loaded in the order you expect - you can't count on the route provider opening and starting up your home controller before it runs other controllers - that is just going to depend on how things are setup. Given the amount of code you have provided here its hard to say what exactly is going wrong as far as order.
That in mind you have a few general options that will fix this:
Always call loadUrls() before you run a $http request. This isn't elegant but it will fix the issue
Wrap all of your $http calls and call loadUrls() in that wrapper. This is slightly better than the previous because if you need to change loadUrls() or make sure it is called only once you can implement that logic later.
You already observed this, but you can change your initialization to be directly in the service rather than in a routine provided by the service. This will fix the issue although it may leave you in a place where you have to update the service every time the url's change.
Live with the error, knowing that when the controller loads it will instantiate and get the correct data at that point in time. I don't often love solutions like this because it could cause errors later that are hard to trace but if you don't like any of the previous options this could technically be ok.
Use an app configuration, which is executed when the application loads (note that not all resources are initialized and injection is not allowed). An example from the documentation:
angular.module('myModule', []).
config(function(injectables) {
// provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
You can use this or a run block to initialize what you want
I'm sure there are other options as well depending on how your code is structured but hopefully this at least gets you started. Best of luck!
I had this same problem, and I fixed it by changing this:
var logoutURL = URL + '/logout';
function sendLogoutHttp(){
return $http({
method: 'GET',
url: logoutURL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
to this
function sendLogoutHttp(){
var logoutURL = URL + '/logout';
return $http({
method: 'GET',
url: logoutURL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}

Resources