Professional Documents
Culture Documents
So I did a talk on AngularJS last night at the Pittsburgh .NET Users' Group. It was a great talk and you
guys asked a lot of great questions. One of my friends that attended suggest people use my blog as a
resource for Angular, and while I do have quite a few posts about Angular, I don't feel like it's quite as
flushed out in that department as I'd like it to be before I wanted my friends plugging it like that. So I've
decided to try to fill that gap, at least as far as Angular goes, over the next few weeks, if I can. (Don't
worry, PGHNUG attendees, I'll still try to get a well commented Angular/Web API solution up on GitHub
soon).
That's fine. It's an easy to understand pattern that is predictable for most other developers using your
service and most importantly, it works.
app.factory('myService', function($http) {
return {
getFoo: function() {
//since $http.get returns a promise,
//and promise.then() also returns a promise
//that resolves to whatever value is returned in it's
//callback argument, we can return that.
return $http.get('foo.json').then(function(result) {
return result.data;
});
}
}
});
app.controller('MainCtrl', function($scope, myService) {
//DEPRECATED: The commented line below WILL NO LONGER WORK in 1.2.0
//since promises are no longer resolved by templates.
//$scope.foo = myService.getFoo();
//make the call to getFoo and handle the promise returned;
myService.getFoo().then(function(data) {
//this will execute when the
//AJAX call completes.
$scope.foo2 = data;
console.log(data);
});
};
And because some of you like to play around, here's a bit of code on plunker showing the promise pattern
for $http calls in Angular:
Because I've been asked by friends what to do in situations where you might have nested or simultaneous
async calls in a controller, I think this blog entry is a really good place to show some examples of that,
since it falls under the same domain, so to speak.
There are of course scenarios where you might have a service method that requires more than one $http
call (or other async call) to be made before you want the service to return. This is where you'd want to use
the $q service mentioned above.