Reputation: 5238
I am building an application with AngularJS that communicates with an ASP.NET Web Api Server.
In the angular client i have couple of services that communicate with the server through the $http core service.
The problem is that i can't return actual results from the http request but only a promise.
Lets say that i have a service that returns an array of tickets (some resource of my application) from the server:
myService.getAll = function () {
var result = $http.get('/api/tickets').then(function (result) {
if (result.status !== 200)
return [];
return result.data;
}, function (err) {
return [];
});
};
What can i do if i want to explicitly return the data of the result (or an empty array on failure) from the service and not a promise?
Is there a way to wait for a response in Angular?
Thanks, Arik
Upvotes: 0
Views: 5971
Reputation: 95064
You can get this functionality if you resort to instead using the XMLHttpRequest
object, however, I strongly suggest against it because it will negatively impact your application.
Yes, it might make it easier for you to understand and write your code, however, it will negatively impact your end-users by locking the browser up while it is "waiting" for the synchronous request to finish. The user will be unable to do anything within their browser, including changing to other tabs, typing in inputs, clicking buttons, and even animated gifs wont animate. css animations won't run, etc. To the end user, your application will look broken until the request finishes.
To top all of that off, synchronous ajax requests have been deprecated in modern browsers, so it's likely they'll be gone completely in a couple of years (if not sooner,) meaning you'll either have to update your application to use asynchronous requests later, or just not support browsers that drop support for sync requests.
The best option is to embrace promises.
myService.getAll = function () {
return $http.get('/api/tickets').then(function (result) {
if (result.status !== 200)
return [];
return result.data;
}, function (err) {
return [];
});
};
Upvotes: 4
Reputation: 1182
There is no way to wait fr the response, but you have to pass data to your controller by implementing callback function, for example you service looks like
myService.getAll = function (callback) {
var result = $http.get('/api/tickets').then(function (result) {
if (result.status !== 200)
return [];
if(typeof(callback)=="function")
{
callback(result.data)
}
}, function (err) {
return [];
});
};
Upvotes: -2