Accessing the device data

Now that the basics of our app are have been implemented, it is time to add some serious data to it. In our case, we want to load the contacts stored on the device that our app is running on so that we can show them in the list that we created earlier.

Accessing native services

You may recall that Ionic is built on top of the Cordova platform, which provides the core interaction with the underlying operating system and hardware. In order to access native services, such as the contact list, we will frequently have to make use of Cordova directly.

In this particular case, we are in a very easy spot; Cordova not only has a full-fledged plugin to interact with the contacts, but also sports a very convenient CLI method to install it.

Go to your project directory and run the following from a terminal or command line:

cordova plugin add org.apache.cordova.contacts

This will install the Cordova Contacts plugin, which will be placed in the following folder:

plugins/org.apache.cordova.contacts

Feel free to inspect the files before we move on. Next, we need to integrate this plugin with Ionic so that we can use it in our app.

ngCordova

Cordova itself knows nothing about either Ionic or AngularJS. So, accessing its services in an Angular fashion will often require wrapper code. Fortunately, there is already an extensive library for this exact end—ngCordova.

To install it, go to the root of your project folder and run the following from a terminal:

bower install ngCordova

This will install everything we need. Next, let's again import it into our app by modifying the app.js and index.html files. In app.js, make sure that your app dependencies now include ngCordova, as follows:

angular.module('phonebook',
  [
    'ionic',
    'ngCordova',
    'phonebook.controllers',
    'phonebook.services
])

Likewise, in index.html, make sure that we import the corresponding JS library, as follows:

<!-- AngularJS bindings for Cordova -->
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>

Adding Cordova contacts to our factory

The last step here is to integrate the Cordova contacts with the contactsFactory service in order to let it serve the contacts available on the device. Open the js/services.js file and make sure that it contains the following:

angular.module('phonebook.services', [])
.factory('contactsFactory', function contactsFactory($q, $cordovaContacts) {
  /**
  * Turns a raw contact into something more suitable for viewing.
  *
  * @paramrawContact
  */
  function processContact(rawContact) {
    return {
      name: rawContact.name ? rawContact.name.formatted : '',
      number: rawContact.phoneNumbers ? rawContact.phoneNumbers[0].value
    }
  }

  return {
    all: function () {
      // It may take some time to fetch all contacts, so we defer it.
      var deferred = $q.defer();
      $cordovaContacts.find({multiple: true}).then(function (contacts) {

        varprocessedContacts = [];
        contacts.forEach(function (contact) {
          processedContacts.push(processContact(contact));
        });

        deferred.resolve(processedContacts);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    }
  }
});

The important parts are highlighted. Let's figure out what is going on:

  • We inject the following dependencies for our factory:
    • $q: This is the AngularJS service that is used to work with promises. This will allow us to create deferred functions, which resolve to a value at a later stage. At that point, something can be done with their results.
    • $cordovaContacts: This is the Cordova contacts plugin itself that is wrapped by ngCordova.
  • Since raw contact data is rather clunky, we define a utility method in order to process it into something more lightweight.
  • We create a promise, which is returned to whoever uses our service. The promise in this case is that at some point, we will deliver either a list of contacts, or an error indicating why we could not do so.
  • We invoke the find() function of cordovaContacts, which is very similar to the MongoDB function with the same name; it simply returns all the available contacts.
  • If we can get the list of contacts, we resolve the promise and hand over the list to the caller.
  • If we cannot get the list of contacts, we reject the promise, indicating that we were not able to get what was requested. An error message created by cordovaContacts is returned to the user.

Our service is now all configured and good to go. There is still one major hurdle though. Emulators have no contacts for us to display! In order to move on, we will first have to take a detour and see how to deploy the app on physical devices before we finally wrap up our app by showing the contacts to the user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.68.28