AngularJS Pattern #1 - async service results
Join the DZone community and get the full member experience.
Join For FreeSpring Quizzo ETE sample code
Hi everyone. If you're looking for examples of potential ways to interact with a Spring app from AngularJS, take a look at the project I worked on with Pivotal's David Turanski for ETE, the Quizzo-ETE application.
It's at github.com/krimple/quizzo-ete. Highlights:
Now here's something I ended up using (but not as well as in here) for the quiz. It's a way to send a request to a Angular service asynchronously and receive a result via a message back to the component.
Asynchronous calls to services in Angular
In Angular, everything is asynchronous as much as possible to provide speed. A call to a $http
service, which performs ajax methods, doesn't immediately return a value. If you decide to split up your Angular controllers and services, so you separate your UI from the calls to your backends, you'll quickly find that it becomes hard to get a response without some extra work.
One way to orchestrate calls is to use the Angular messaging framework, built into the $scope
object. For example, in our controller we can execute a call to fetch games we're able to play right now, but we won't get the response right away. So, we can subscribe to a message, sent by our service, which will then come back to us with data. See this simple JSFiddle for an example:
The service uses a passed $scope
variable. I've also injected a $rootScope
into the service. Using that one would allow us to broadcast the message to any interested party.
Published at DZone with permission of Ken Rimple, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Why You Should Consider Using React Router V6: An Overview of Changes
-
Microservices: Quarkus vs Spring Boot
-
Low Code vs. Traditional Development: A Comprehensive Comparison
-
Implementing RBAC in Quarkus
Comments