Select Page

The Setup

Welcome back to another installment of the of building a simple REST application with AngularJS! In the previous lesson, we learned how to consume a REST API in AngularJS using $http. In this lesson, we are going to see an alternate approach using an automatically generated service from the LoopBack AngularJS SDK that is compatible with $resource.

If you haven’t had a chance to check out Part 1 and Part 2 of the series, be sure to check them out first as this post builds heavily on top of them.

The project has two parts: the REST API and the website that consumes it. The REST API repository remains unchanged and we will be working from the angular-sdk branch of the website repository.

Simple Rest API Simple Rest Website

Generate the Service

SLC SDK CLI

The LoopBack AngularJS SDK gives us the ability to generate an AngularJS service based off of our Node.js model using the cli tools that come with the SDK. So just to clarify why I like this, we are able to generate an entire REST API using StrongLoop and THEN! generate an AngularJS service to consume the generated REST API. I do not think code generators are the answer for everything and one should understand what is happening under the hood when the use them but for rote work… I admit… I am lazy and I hate the tedium.

The commands we are going to use are operating on the assumption that the simple-rest-api and simple-rest-website directories are siblings to each other. If this is not the case, you may need to update the commands appropriately.

The first thing we need to do is to navigate to the folder in the simple-rest-api project where we want to generate our service. We will jump into the client folder since it is empty and a good of choice as any.

cd simple-rest-api
cd client # or wherever you want the generated file to go...client is conveniently empty

From here, we are going to use the lb-ng command to generate our service. We are telling it to generate our service based on server.js and call it lb-services.js.

lb-ng ../server/server.js lb-services.js # path_to_application_js path_to_file_to_write

And now we are going to move the generated service into the app directory of our simple-rest-website.

mv lb-services.js ../../simple-rest-website/public/app/

Phase one of Operation LoopBack SDK complete!

AngularJS Integration

We need to flip a few switches and turn a few knobs to integrate our service with our AngularJS application.

We need to include the angular-resource.min.js and lb-services.js source files into our application.

<script src="//code.angularjs.org/1.3.0/angular-resource.min.js"></script>
<script src="app/lb-services.js"></script>

Then we inject the lbServices submodule into our main application module.

angular.module('SimpleRESTWebsite', ['lbServices'])

Because we have separated our API and our web application into two distinct parts, we need to update the urlBase variable in lb-services.js to point to http://localhost:1337/api instead of /api.

var urlBase = "http://localhost:1337/api";

Phase two of Operation LoopBack SDK complete!

Updating the MainCtrl

We need to update the MainCtrl to use the Item service instead of the ItemsService.

angular.module('SimpleRESTWebsite', ['lbServices'])
    .controller('MainCtrl', function (Item) {
        //...
    });

And then update the getItems method to use Item.find.

function getItems() {
    Item.find(
        function (result) {
            main.items = result;
        });
}

We will then update createItems to use Item.create.

function createItem(item) {
    Item.create(item,
        function (result) {
            initCreateForm();
            getItems();
        });
}

We will modify updateItem to use Item.upsert. Upsert!? Whaaaa… after a quick Google search I found the explanation below. Thanks Wiki! Although I am going to let you look up portmanteau on your own.

Some database implementations adopted the term “Upsert” (a portmanteau of update and insert) to a database statement, or combination of statements, that inserts a record to a table in a database if the record does not exist or, if the record already exists, updates the existing record. It is also used to abbreviate the “MERGE” equivalent pseudo-code.

function updateItem(item) {
    Item.upsert(item,
        function (result) {
            cancelEditing();
            getItems();
        });
}

We are in the homestretch now… deleteItem uses Item.deleteById.

function deleteItem(itemId) {
    Item.deleteById({id: itemId},
        function (result) {
            cancelEditing();
            getItems();
        });
}

Operation LoopBack SDK complete!

SLC SDK

Review

I found working with the Loopback AngularJS SDK to be really pleasant and low friction. The AngularJS SDK is installed with the StrongLoop package and so if you are using it to generate your REST API it is REALLY easy to use it to generate your AngularJS services as well.

The general steps we executed are as follows

  1. From the command line, start in the directory where you want to generate your service.
  2. Use lb-ng to generate your service
  3. Move that service into your AngularJS application
  4. Include ngResource and your service into your application.
  5. Inject the lbServices into your AngularJS application.
  6. Consume your generated service in the appropriate controller.

I also found the generated service to be very well documented and easy to read so I recommend reading through that as well.

Resources

LoopBack AngularJS SDK Documentation

Simple Rest API Simple Rest Website