Contents


Develop an Angular Ionic mobile app using IBM Cloud Push services

Set up, configure, and test Push notifications the Angular way

Comments

Ionic is a popular framework for creating hybrid cross-platform mobile apps using web technologies. Ionic is based on the AngularJS framework and uses Cordova to expose native mobile device capabilities (like Push, Camera, or GPS) to the JavaScript code.

This tutorial shows how to create a starter Ionic mobile app that uses IBM Cloud Push services via the IBM bms-push Cordova plugin. Using the plugin in this way allows access to the push service from within your Angular contollers. This tutorial takes you through the minimum steps needed to properly use the bms-push plugin in an Ionic AngularJS mobile app. It describes how to create an IBM Cloud Push AngularJS service using the plugin and then how to configure and call the service in the "Angular way."

Following the steps below will result in the same code and give you a working knowledge of using IBM Cloud Push in an AngularJS app.

1

Create a mobile back end in IBM Cloud

To create a new mobile back end on IBM Cloud:

  1. Log into the IBM Cloud dashboard and create a new application.
  2. Select Boilerplates, then the Mobile First Starter boilerplate.
  3. Type a unique name for the app and click Finish.

The app should now be created and will contain a sample To Do app running in the Node.js runtime environment using StrongLoop. It will also contain services for a Cloudant NoSQL database, push notifications capabilities, and IBM Cloud App ID services.

We will only be using the push notifications service in this tutorial. Test the new created app by opening a web browser and going to the app route.

2

Create the Ionic app

To install Ionic and use its command-line tools to create a new app:

  1. Install Node.js.
  2. Install Ionic and Cordova command-line tools using npm install -g cordova ionic.
  3. Change to the folder where you would like to create the app and create a new ionic project using ionic start APP-NAME side-menu. (We have opted to use the side-menu code template only to make this more of a real-world example.)
  4. Step into the newly created project folder using cd.
  5. Add the target mobile platforms for your application using ionic platform add android ios.
  6. Add the IBM Cloud Push cordova plugin using cordova plugin add bms-push. (This will also add the IBM Cloud Core plugin (bms-core).)
3

Create the Angular IBM Cloud Push service

Open the app in your favorite IDE and create a file called services.js within the www/js folder and add the following code:

angular.module('starter.services', [])

.service('BluemixService', function ($window, $q) {

    this.connect = function (appGuid, clientSecret) {
        // create deferred object using $q
        var deferred = $q.defer();
        if (window.cordova) {
            $window.BMSClient.initialize(BMSClient.REGION_UK);
            $window.BMSPush.initialize(appGuid, clientSecret);
            var success = function (message) { //fires on success of MFPPush.registerDevice
                var deviceId = JSON.parse(message).deviceId;
                deferred.resolve(deviceId);
            };
            var failure = function (message) { //fires on failure of MFPPush.registerDevice         
                deferred.reject(message);
            };

            var options = {
                ios: {
                    alert: true,
                    badge: true,
                    sound: true
                }
            };

            var notification = function (notification) {
                //if we don't have this then alerts are NOT displayed at all when the app is open
                alert(notification);
                //this will just pop up a default alert box when the app is open. When the app is not open, the alert will be handled by the native alert process 
                //instead of the default alert pop up you could use something like the cordova toast plugin here
                // eg $cordovaToast.showShortTop(notification).then(function(success) {
                        // success
                      //}, function (error) {
                        // error
                      //});
            };
            $window.BMSPush.registerNotificationsCallback(notification);
            $window.BMSPush.registerDevice(options, success, failure);
            deviceId = deferred.promise;
        } else {
            deviceId = "Web View";
        }
        return $q.when(deviceId);
    };
})
4

Set up the app to use the services.js file and our new push service

Open the www/index.html file and add a link to our new services.js file. You will see a section containing links to app.js and controllers.js; this new link should be added there.

    <script src="js/app.js"/>
    <script src="js/controllers.js"/>
    <script src="js/services.js"/>

Open the app.js file and change the line beginning angular.module from angular.module('starter', ['ionic', 'starter.controllers']) to angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']). This makes the app aware of our new services module within the services.js file.

Add these constants under the line updated above:

.constant('appGUID', 'appGUIDFromBluemixServiceHere')	
.constant('clientSecret', 'clientSecretFromBluemixServiceHere')

The values for appGUIDFromBluemixServiceHere and clientSecretFromBluemixServiceHere are obtained from the IBM Cloud Push service. Open the service in the IBM Cloud dashboard, select the Configure menu and click the Mobile Options button near the top right of the page to obtain these values.

Note for production apps: These values should never be stored in your code in a production app. They should be supplied to the app from its back end, usually in a response to a successful logon.

5

Use the service

The service will be used via a call from one or more controllers. For our example, we will add a call to the doLogin function within the AppCtrl controller included in the starter template.

Open the www/js/controllers.js file and locate the AppCtrl controller. Inject the new BluemixService to the AppCtrl controller by changing this line from .controller('AppCtrl', function ($scope, $ionicModal, $timeout) { to .controller('AppCtrl', function ($scope, $ionicModal, $timeout, BluemixService, appGUID, clientSecret) {.

Note that we have also injected the appGUID and clientSecret constants we defined in app.js earlier. In a production app, these should be supplied to the controller by some dynamic means so they are not stored in the code of the app.

Change the doLogin function (located within the AppCtrl controller) from:

// Perform the login action when the user submits the login form
    $scope.doLogin = function () {
        console.log('Doing login', $scope.loginData);

        // Simulate a login delay. Remove this and replace with your login
        // code if using a login system
        $timeout(function () {
            $scope.closeLogin();
        }, 1000);
    };

to:

// Perform the login action when the user submits the login form
    $scope.doLogin = function () {
        console.log('Doing login', $scope.loginData);

        BluemixService.connect(appGuid, clientSecret).then(function success(response) {
            //we were successful and the response contains the deviceID supplied by the IBM Cloud push service
            console.log("We registered OK. The deviceID of this device is: " + response);
        }, function failure(response) {
            //Registering for push did not work
            console.log("Registering for push did not work");
        });

        // Simulate a login delay. Remove this and replace with your login
        // code if using a login system
        $timeout(function () {
            $scope.closeLogin();
        }, 1000);
    };
6

Configure the plugins and test

Now all that remains is to set up the push and core plugins for your chosen platforms. The process is quite involved and subject to change, so out of scope for this tutorial. The process is described in detail on GitHub. Please note a few steps have already been covered in this tutorial.

Success or failure of this app is simply logged to the console, and push registration only works if called from a device or emulator (not a browser, so running the app using the ionic serve command will not call the push registration). You will need to view the emulator or device log to see this app working.

Conclusion

Ionic and Cordova are a popular combination for building hybrid mobile apps, but not all Cordova plugins are designed for use in an AngularJS framework like Ionic. This can be particularly frustrating for novice Ionic developers, and can end up costing you many lost hours trying to figure out how to make them work together. I hope this tutorial is helpful to those of you who want to use the IBM Cloud push service in the correct Angular way.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing, Web development
ArticleID=1043832
ArticleTitle=Develop an Angular Ionic mobile app using IBM Cloud Push services
publish-date=03242017