Hello Backend: Your Second Ionic Framework App

Hello Backend: Your Second Ionic Framework App

posted in: Uncategorized | 14

In the first post of this series, Hello World: Your First Ionic Framework App, we learned how to create a basic app with views, routing, and controllers. We will continue with that app structure and look at how to layer on a factory to talk to a backend. We’ll be using the Random User Generator API and you can follow along on the Ionic Playground.

Quick Review

Just as a quick review, we have two states, main and page2, and a controller for the main state.

angular.module('ionicApp', ['ionic'])

.controller("MainCtrl",function(){
  console.log("Main Controller says: Hello World");
})

.config(function($stateProvider, $urlRouterProvider){
  $stateProvider

  .state('main', {
    url: "/main",
    templateUrl: "templates/main.html",
    controller: 'MainCtrl'
  })
  
  .state('page2', {
    url: "/page2",
    templateUrl: "templates/page2.html",
  })
  
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/main');
});

Goal

Our goal by the end of this tutorial is for our page2 state to have a list of 10 random users fed from the API. To accomplish this, we will create a factory that will handle requesting the data from the API. We will call this factory from our controller and pass the data from the controller to our view.

Factory

Let’s create the skeleton a factory called userService with one method: getUsers.

.factory('userService', function() {
	return {
		getUsers: function(){
		
		}
	}
})

This getUsers method simply needs to call our API endpoint: https://randomuser.me/api/?results=10 using an HTTP GET request. To do this, we will need to use the $http service.

.factory('userService', function($http) {
	return {
		getUsers: function(){
		
		}
	}
})

We will call the API endpoint using the $http.get method. $http.get returns a promise, so we will want to handle that promise by adding a .then call after our $http.get call.

.factory('userService', function($http) {
	return {
		getUsers: function(){
			return $http.get('https://randomuser.me/api/?results=10').then(function(response){
				
			});
		}
	}
})

What we want to do in this .then method is process the raw response and return the array of users to our controller.

.factory('userService', function($http) {
	return {
		getUsers: function(){
			return $http.get('https://randomuser.me/api/?results=10').then(function(response){
				return response.data.results;
			});
		}
	}
})

This return of data is actually returning through a promise. This means when we call this method from our controller, it will need to expect a promise which will contain the array of users.

Read More: Ionic: Using Factories and Web Services for Dynamic Data
Read More: Promise-Based Architecture in an Ionic App

Controller

Now that we have a factory, let’s look at calling it from our controller. First, we will need to give our page2 state a controller and add the userService to the controller.

.controller("Page2Ctrl",function(userService){

})

… and configure the state accordingly…

.state('page2', {
	url: "/page2",
	templateUrl: "templates/page2.html",
	controller: "Page2Ctrl"
})

Now, we’re ready to call our factory. Remember, it returns a promise. When we get the response back, we will store it to $scope.users.

.controller("Page2Ctrl",function($scope, userService){
	userService.getUsers().then(function(users){
		$scope.users = users;
	});
})

Now, this data is exposed to our view.

Read More: Controllers in Ionic/Angular

View

Now, let’s take our users array and bind it to a list using ng-repeat.

<ion-content class="padding">
	  <p>I am Page 2!</p>
	  <ion-list>
			<ion-item class="item-avatar" ng-repeat="item in users">
				<img src="{{item.user.picture.thumbnail}} " />
				<h2>{{item.user.name.first}} {{item.user.name.last}}</h2>
				<p>{{item.user.location.city}} {{item.user.password}}</p>
			</ion-item>
		</ion-list>
</ion-content>

… and we should end up with something like this:

Page2 Output

Read More: Creating Views with Ionic

Conclusion

With some fairly simple additions, our little Hello World app is now talking to a backend API. This is another basic building block of most Ionic Apps. Questions? Feel free to leave them in the comments.

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada.

14 Responses

  1. Hi Andrew,
    http://forum.ionicframework.com/t/nested-tab-for-flow/33932?u=sssharma , this is where i put up my problem , please let me know , How to solve this issue.

    Regards
    Shivam

  2. Hi,

    Sorry for the layman question but in

    .controller(“Page2Ctrl”,function($scope, userService){
    userService.getUsers().then(function(users){
    $scope.users = users;
    });
    })

    Where do you declare ‘users’ in ‘function(users)’? But that same ‘users’ where is it declared?

    Thanks

  3. Great article by the way, it was really clear up to that point 🙂

  4. Why use Factory instead of Service… they will both do the same, but aren’t services preferred?

    • Not sure. I’ve always seen and used factories (partially because I preferred the syntax), but yes, they are more or less the same. Do you have any articles that say why services may be preferred?

  5. Mauro Stepanoski

    There is a little mistake in the last part:

    {{item.user.name.first}} {{item.user.name.last}}
    {{item.user.location.city}} {{item.user.password}}

    This code will trigger an error when trying to load the first thumbnail. To solve it, you should do in this way:

    {{item.user.name.first}} {{item.user.name.last}}
    {{item.user.location.city}} {{item.user.password}}

  6. Eren Ogretici

    hey, when i run this code, i get “Failed to load resource: net::ERR_FILE_NOT_FOUND {{item.user.picture.thumbnail}} (0,0)”. after 1 sec of this error, code works fine(i get users info). Why is that? Thank you for awesome help btw <3

  7. I can’t get any data from the API, the Page2 only shows the Header Bar

  8. wow, great job! awesome tutorial.

Leave a Reply