Angular PhoneCat tutorial using a Grails backend

publish on 22/04/2014 by Benoit Wickramarachi

An example on how to replace Grails views (gsp) and controllers by Angular Framework

Angular being more and more popular I decided to try using it for one of my new projects. As I'm starting to learn Angular, I followed the excellent tutorial on the Angular website http://docs.angularjs.org/tutorial. In this tutorial there is no particular backend, only JSON files emulating GSON responses from a backend. I decided to create a backend using Grails.

- id for a Phone object was renamed to phoneID because it was a String and I prefered to keep DB generated ids.- id for a PhoneDetail was also renamed to phoneId for the same reason.- One of the fields in the Camera object is named Primary which is a reserve keyword, so I renamed it to primaryCamera.

Because of those modifications, I couldn't use default object to JSON converter from Grails.I had to register 3 customs JSON converters, one for Phone, PhoneDetail and Camera objects.

Now that the data model is defined let's fill the database up using datas provided by JSON files from the tutorial.

To do so I copied each required artefacts from 'app' folder to web-app so that Grails can have access to all Javascripts, CSS, images,... files from the tutorial:

I also copied the phones folder (containing all JSON files) to be able to easily access them within Grails.

Now, we need to load each JSON files into the database. To do so, I parsed each file in the bootstrap.groovy and converted the content (String) to a JSON object, which I then used to construct a Grails domain object using Data binding (because a JSON object is an array, we can just pass it as a param to each domain object constructor).

def jsonPhones = grails.converters.JSON.parse(file.text)

The only manual operation I needed to do was for the 3 exceptions that I had (2 ids renamed to phoneId, and primary renamed toprimaryCamera). For those properties, I set them directly before persisting each object into the Database:

And it's pretty much it, the backend is ready. Of course we could have add CRUD operations and error management but I wanted to keep it as minimal as possible.

Step 3: Replace Grails views with Angular framework

I copied all the required artefacts from the Angular PhoneCat tutorial under Grails /web-app folder in an earlier step. Now I have to add a new Angular module in the Resources plugin to include them later in a GSP:

Conclusion

It was really easy to replace Grails Controllers and views by Angular Framework. Grails converter made it easy to provide JSON data to Angular andCRUD operations can also be added without pain using Grails REST API. I decided to stick with Angular and see how it goes in a real life project.