Multiple service calls as data for AngularJs

angularjsWe need a composition layer for the GUI. It should combine the data from multiple services into one interactive web page. AngularJs comes to mind.

My next step in AngularJs (first step here) is to get data from multiple REST calls. The trigger is a button and the data is presented side-by-side.

First the HTML code. The button fires the getData function on data-ng-click. By using the selectedId in the function call the input is passed to the function.

<div ng-app="multiple" ng-controller="leftrightctrl">
  <div class="row">
    <input type="number" ng-model="selectedId" />
    <button data-ng-click="getData(selectedId)">Click me!</button>
  </div>
  <div class="row">
    <div class="col-md-6">
      <pre>November: {{left.name}}</pre>
    </div>
    <div class="col-md-6">
      <pre>December: {{right.name}}</pre>
    </div>
  </div>
</div>

In javascript I defined a function to get the left and the right. With getData I call both. The data is from a REST service. It is called with the id and a date. Left is november (2015-11-01) and right is december (2015-12-01).

angular
  .module('multiple', [])
  .controller('leftrightctrl', function ($scope, $http) {
    $scope.left = null;
    $scope.right = null;
    $scope.getLeft = function (id) {
     return $http.get("http://localhost/service/api/multiple/" + id + "/2015-11-01")
                 .then(function (response) {
                   $scope.left = response.data;
                 });
    };
    $scope.getRight = function (id) {
     return $http.get("http://localhost/service/api/multiple/" + id + "/2015-12-01")
                 .then(function (response) {
                   $scope.right = response.data;
                 });
    };
    $scope.getData = function (id) {
     $scope.getLeft(id);
     $scope.getRight(id);
    };
});

Reading code from others is the first step in shu-ha-ri. I’m learning.
plnkr with a live version of the code.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s