heidloff.net - Building is my Passion
Post
Cancel

How to write AngularJS Frontends for LoopBack Applications

With the Node.js API framework LoopBack you can easily provide REST APIs for your applications. In order to build web frontends LoopBack provides an AngularJS JavaScript SDK. Below is a sample application which demonstrates how to use this SDK.

Download the sample application from GitHub.

In AngularJS applications you typically build views that interact with services via controllers. The services access data from the server-side applications. Obviously you can write your own services which invoke the REST APIs of your LoopBack applications directly. But LoopBack makes this even simpler via the AngularJS SDK. With the SDK client side JavaScript libraries are generated for your REST APIs so that the controllers can simply invoke JavaScript APIs rather than REST APIs.

The sample application demonstrates how to build a web based frontend for a simple Approval Request scenario. Approval requests have titles, descriptions, requesters and approvers.

image

Here is the code snippet of the controller that returns all approval requests. The class ApprovalRequest is provided by the LoopBack SDK.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
angular.module('angularApp').controller('RequestsController', ['$scope', 'ApprovalRequest', function($scope, ApprovalRequest) {
  $scope.requests = [];
  function getRequests() {
      ApprovalRequest.find().$promise
        .then(function(results) {
          $scope.requests = results;
        }, 
        function(err) {
          $scope.requestsError = err.statusText;
        }
    );
  }
  getRequests();
}]);

Authentication is also very easy from Angular. Just invoke the Person.login function.

The file lb-services.js with the JavaScript APIs for your own business objects defined via LoopBack is generated either via command line or via Grunt. The approval request sample application uses the Grunt plugin to build the file automatically and to put it in the Angular application.

1
2
3
4
5
6
7
8
9
10
11
12
loopback_sdk_angular: {
  options: {
    input: '../server/server/server-gen.js',
    output: 'app/scripts/services/lb-services.js'        
  },
  production: {
    options: {
      apiUrl: 'http://localhost:3000/api'
      //apiUrl: 'http://collaboration-nheidloff-1534.mybluemix.net/api'
    }
  }
},

For details check out the project on GitHub.

Featured Blog Posts
Disclaimer
The postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions.
Trending Tags