Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

AngularJS Pattern #1 - async service results

DZone's Guide to

AngularJS Pattern #1 - async service results

· Web Dev Zone
Free Resource

Prove impact and reduce risk when rolling out new features. Optimizely Full Stack helps you experiment in any application.

Spring 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.

With SDKs for all major client and server side platforms, you can experiment on any platform with Optimizely Full Stack.

Topics:

Published at DZone with permission of Ken Rimple, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}