Build a Hybrid Application with the Ionic Framework and Azure Mobile Services, Part 3: Wiring Up The Backend

In Part 2 of this series I discussed how to set up our mobile user interface with Ionic and we prepared our Angular controllers and views to accept data from our Azure Mobile Service backend. In this article, we are going to create our Azure Mobile Service, publish it to the cloud, and start sending and receiving real data from within our Ionic application. Without further ado, let’s get started!

Creating the Azure Mobile Service

Prerequisite: To follow along you will need a Windows Azure account. All services utilized in this tutorial are free.

Before we make any modifications to our Ionic application we need to first create our Azure Mobile Service. To do this, log into your account and proceed to the Azure portal. From here, follow these steps:

1.) In the left pane, click on Mobile Services.
2.) In the bottom left corner, click New beside the + sign.
3.) Select Compute > Mobile Service > Create

Create Mobile Service

Create Mobile Service

4.) Enter the requested URL for your mobile service and select the database and region. Azure offers a free 20mb SQL server database to get you started. For backend select .NET as that is what we will be using for this demo. (JavaScript backend is also an extremely viable option and is generally easier to get up and running.)

Database Options

Database Options

5.) Next, enter a login and password for your mobile service database.

*At this point Azure will take a minute or so to create your database and mobile service. Once complete, click on the mobile service tab and select your service from this list provided.

6.) Under Get Started select Connect an existing HTML app.
7.) Select and download the provided solution under ‘Download and publish your service to the cloud‘.

Download Solution

Download Solution

8.) Before you exit, select Configure from the top navigation menu. Scroll down to Cross-Origin Resource Sharing (cors) and add an allowed origin of *. This will allow our mobile application (with the proper API-KEY) to access our service. *Update* As pointed out in the comments below Android users may also need to install the cordova whitelist plugin to properly fetch the data from our AMS API.

Configure CORS

Configure CORS

Configure and Publish the Mobile Service

Open the solution that you downloaded from step 7 in the previous section. In it you will find the basic boilerplate needed to get started creating our backend service using .NET and Entity Framework code first. Let’s begin customizing this solution to fit our needs.

1.) As a quick cleanup, delete the sample Todo model and controller that came with the solution.
2.) Next, under the Data Objects folder, let’s create our Goal entity that we will use in our Goal Setter application.

3.) Under the Models folder, edit your DbContext class to include your Goal DbSet (and delete the Todo DbSet). This will tell Entity Framework code first to create this as a table in our database.

4.) At this point we are ready to scaffold our database using Entity Framework Code First Migrations. Open up the Package Manager Console and run the following commands.

5.) Now that we have our database, let’s add a pre-built Azure Mobile Service controller. Right click on the controllers folder and select Add > Controller > Microsoft Azure Mobile Services Table Controller. This will give us all we need to start performing CRUD operations against our database through our Ionic mobile application. For more advanced scenarios and custom use cases, it will likely be best to create your own custom Web API controllers to fit the needs of your business or application.

6.) To test that everything is working, hit F5 to run the project. When the browser window appears click Try it out. Your service end points will be automatically documented for you and sample request and response for each endpoint provided. It’s time to publish our solution to the cloud!

Automatic Documentation

Automatic Documentation

Publishing to Windows Azure

Now that we have our mobile service solution built, let’s publish it to the cloud so we can hit it from within our Goal Setter application.
1.) From within Visual Studio right-click on your main project file and select Publish. Since we are using the solution preconfigured for us when we created our mobile service our publish profile will already be completed with the appropriate information.

2.) Click on the Preview tab and select Publish. After a minute or so a browser window will pop up and if all went well you will see a message stating your mobile service is up and running. Now let’s hook up our mobile application to talk to our newly published service!

Publish Confirmation

Publish Confirmation

Wiring Up the Mobile Application

From within your favorite IDE open up the GoalSetter project. It’s time to swap out our fake data with the legitimate backend we just created.

1.) Download the required Azure Mobile Services JavaScript file and add it to your project.

2.) To make interacting with our service through Angular more straightforward let’s also download and include a helper library from Terry Moorell, Angular-Azure. This Angular module will wrap our Azure service calls in Angular promises, making it dead simple to send and receive our application data.

3.) Add a reference to the Angular-Azure module in your main app.js module as well as an app wide constant for your API URL and API Key. This information can be found under your Azure mobile service on portal > Get Started > Connect an Exisiting HTML App > Connect your app and store data in your service.

4.) Next, let’s update our GoalSetterFactory.js to make calls to our cloud service. First, inject the ‘Azureservice’ module we included in the previous step then modify the public API to use this service. We will also include $ionicLoading in order to display a ‘Loading…’ message while our data is being sent and retrieved.

5.) It’s time to update our Goal controller to interact with our mobile service. Please note we will also need to modify the goal dates returned from our service to compare and display as MM/DD/YYYY format. I added a GoalSetterHelper factory to the project to contain this logic and any other basic functions that may be needed throughout the application. All other changes to the controller are minimal.

5.)Next, we need to update our create-goal.html page with some basic validation to require both fields and ensure a date is being entered in a valid format. To accomplish this we will use Angular’s built in form validation and disable the submit button while the form is not valid using ng-disabled.

6.) The last thing we need to do is update our Statistics controller to properly adjust the dates being returned from our service.

Test Run the App!
Now that all of our adjustments are complete and our Azure Mobile Service is up and running, let’s see it in action to ensure everything is working properly. Open up your command line from the root of the Goal Setter application and run these commands.

Navigate to the Goals tab and select Add New Goal. Fill out the form and submit, you will now see the newly added goal appear in your Goal’s page, straight from our Azure Mobile Service. Checking and unchecking the goal will also update the goal’s status in your database.

Add Goal Screen

Add Goal Screen

Goal Added to DB

Goal Added to DB

We now have a fully functional mobile application communicating with an Azure Mobile Service backend. In the next article, we will discuss how to add caching to our application as well as incorporating ngCordova to store our data locally to the device. All code for this article can be found on GitHub. As always, if you have any questions or run into any issues feel free to drop me a comment. Until next time, happy coding!

  • Justin Schuldt

    I came here from googling ‘ionic push azure’, nice work through your series! Your repo is one of the best Ionic and Angular tutorials I’ve seen.

    I’m really interested to see how you handle push notifications. I’ve been doing it with Azure’s mobile client library and PhoneGap’s PushPlugin, but I would really love to see it done the angular way, with ngCordova.

    Thanks, keep up the good work!

  • Btroncone

    Justin, I will definitely look into adding a section regarding push notifications with Azure Mobile Services. Thanks for reading and the kind words!

  • Hamza Alazzeh

    I really loved and enjoyed your intensified lessons, it gave me everything I needed in order to build a hybrid application suing ionic and azure mobile services, I’m going to use your lessons as a reference
    Do you have any idea on when to expect part 4 of this series and the push notification part if it is on your plan?

  • Btroncone

    Hamza, thanks for reading and commenting! I hope to have another article out detailing ngCordova integration and caching within the coming week. As far as push notifications, with the upcoming release of Ionic push I was hoping to detail that in a future article. That timeframe is dependant on the official release of Ionic push. I may also discuss integrating Azure push notifications to detail both options pro’s and/or con’s. Once again, thanks for reading and I apologize for the delay between articles!

  • nick_dow_ling

    Great article. I could get my app to work fine following these instructions when served in the local web browser but in the android emulator and actual phone it would not fetch the data until I installed the cordova whitelist plugin (cordova plugin add cordova-plugin-whitelist).

    • Btroncone

      Thank you very much for your comment! When I originally wrote the article I tested on iOS simulator and device but not on Android. I am going to update the article to reference your suggestion in case others run into similar issues. Thanks for the great advice!

  • Sebasti├ín Rojas Ricaurte

    Theres not possible to upload to azure mobile services an existing ASP.NET Web API backend application?

  • Fabio

    Hi Brian
    thanks a lot for your tutorial, One of the best For Angular and Ionic.
    I ask you to make one for push notification service…. I look for a week, but I never find something of usable.
    Please , if you have time make one for push notification service on ionic cordova app.
    Thanks a lot

    • Btroncone

      I apologize for not getting the push notification post out, I have gotten involved with some other projects. I still have this on my radar if I have some free time in the future. Thanks again for reading and the kind words!

      • Manju Dogra

        Hi Brian,
        I was looking for some how to information on receiving push notifications from Azure Notification Hub in an Ionic app ..could you help ..thanks M

  • Dilip Singh

    Hello Brian

    thanks for this great tutorial.

    I have followed this tutorial and everything worked except CORS issue

    How can i fix this problem. I have tried all what i have generally implemented the same in other solutions
    Add cors by adding a messageHandler etc.

    XMLHttpRequest cannot load$inlinecount=allpages. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access. The response had HTTP status code 404.

    i can share code base if you or anyone can help me put here,

    Contact me :

    • Btroncone

      Thanks for the feedback! Do you have this code on GitHub? If so, please share a link, thanks!

      • Dilip Singh

        I dont have it on github but i followed all steps in the tutorial and finally it was a replica of code provided by you.

        Later i have used your code with providing my APIURL and API KEY and i had the same problem.

        I suspect problem in on Azure configuration but not sure.

        Is it possible if you can provide me a working code (with apiurl and apikey) for test with the settings on azure.

        thanks again .

        • Thomas Debye

          Hi, Did you solve the cors issue?
          I can’t fix the cors issue.

      • Dilip Singh

        Another observation:

        If i simply use the sample app generated from azure , all works(with MobileServices.Web-1.2.5.js file) but if i use “azure-mobile-service.module” i face the CORS issue again.

        I have tested this with Todolist sampleapp

Next ArticleOptimize your Ionic Testing with Wallaby.js, Bard.js, and WebStorm