Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / AWS

How to Connect an Ionic Angular Application to AWS

5.00/5 (2 votes)
26 Dec 2017CPOL7 min read 25.7K  
Connecting Angular app to AWS Mobile Hub
In this tutorial, I'm going to show you how to connect an Angular application to AWS Mobile Hub

TL;DR

Since Ionic is powered by Angular, this will hold true for any Angular application, and you will be able to use this knowledge in any Angular web application with minimal changes.

The Technologies

Just so we get all the unknowns out of the way for anyone that may have been sitting under a rock for the past, well, forever.🙈

AWS

Amazon Web Services (AWS) is a flexible, cost-effective, easy-to-use cloud computing platform.

Ionic Framework

If you've been following my blog, then I don't have to give any special introduction to Ionic framework. But, for the sake of brevity, their website says that:

Ionic framework is the beautiful, free and open source mobile SDK for developing native and progressive web apps with ease.

If you're looking for an introduction to Ionic framework, you can check out the first post in the series:

Ionic + AWS = ❤️

Ionic partnered up with the AWS Mobile Team to build the official Ionic AWS starter project. This project generates an Ionic app complete with a pre-configured AWS Mobile Hub project ready to go, along with pre-configured pages and utilities wired up to Amazon Cognito for user identity management, DynamoDB for application data, S3 for file storage, and Pinpoint for analytics.

Demo Project

You can check out the code of the demo that I made, based on the above-mentioned official Ionic AWS starter project on Github.

You can even check the website demo of the project in action here. Yes, loving the Ionic's superpower of write once deploy everywhere. 💪

Step by Step

In this post, I'll first show you how to set this Ionic AWS starter project. If you're looking to learn more about all the storage options on AWS, you can check out this tutorial: Exploring Storage Options on AWS

Install the Required Prerequisites

First, make sure you have the latest Ionic version (at the time of this writing, the current latest version is 3.19.0):

npm install -g ionic@latest

In order to install AWS CLI (Command Line Interface), you need to have Python3 installed. If you're on Mac, chances are that you already have it installed. If not, here are the installation details. If you use brew on a Mac, then a simple brew install python3 is all you need, as that will install pip for you as well.

pip is a package manager for packages written in Python (like npm is for Node projects).

⚠️ To be honest, installing AWS CLI was a pain for me. In the end, a simple brew install awscli (as outlined in this StackOverflow answer) worked like a charm. I'm keeping the below instructions in case you get stuck on a similar problem, so you don't have to go on a Google quest. If none of these solutions help and you're still stuck, hit me up in the comments and I'll try to help. 💪

If you get an error like:

An unexpected error occurred during the `brew link` step 
The formula built, but is not symlinked into /usr/local Permission denied @ d
ir_s_mkdir - /usr/local/Frameworks Error: Permission denied @ dir_s_mkdir 
- /usr/local/Frameworks 

then first run brew doctor and after that, sudo chown -R $(whoami) $(brew --prefix)/* as explained in this StackOverflow post.

If you get an output like:

Warning: python3 3.6.3 is already installed, it's just not linked. 
You can use `brew link python3` to link this version. 

And if then after running brew link python3, you get an error like:

Linking /usr/local/Cellar/python3/3.6.3... 
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks 

you can solve it with the following two commands, as explained here:

sudo mkdir /usr/local/Frameworks
sudo chown $(whoami):admin /usr/local/Frameworks 

After this, the linking should work fine.

To install AWS CLI, run:

pip install awscli --user -U

⚠️ notice the --user -U. In case you're looking at the official Github repo, their command fails, because of the reason explained in this StackOverflow answer. Using those flags solves it.

To confirm that you installed the AWS CLI correctly, run aws --version and you should get something like:

aws-cli/1.11.190 Python/3.6.3 Darwin/17.2.0 botocore/1.7.48

Create a New Ionic Project

To create a new Ionic project using this AWS Mobile Hub starter, run:

ionic start IonicAWS aws

The output of the command will look something like this (if you said No to platforms question):

✔ Creating directory ./IonicAWS - done!
✔ Downloading and extracting aws starter - done!

? Would you like to integrate your new app with Cordova to target native iOS 
and Android? No
✔ Personalizing ionic.config.json and package.json - done!

Installing dependencies may take several minutes.

  ✨   IONIC  DEVAPP  ✨

 Speed up development with the Ionic DevApp, our fast, on-device testing mobile app

  -  🔑   Test on iOS and Android without Native SDKs
  -  🚀   LiveReload for instant style and JS updates

 ️-->    Install DevApp: https://bit.ly/ionic-dev-app    <--

> npm i
✔ Running command - done!
> git init
> git add -A
> git commit -m "Initial commit" --no-gpg-sign

♬ ♫ ♬ ♫  Your Ionic app is ready to go! ♬ ♫ ♬ ♫

Run your app in the browser (great for initial development):
   ionic serve

Install the DevApp to easily test on iOS and Android
   https://bit.ly/ionic-dev-app

Run on a device or simulator:
   ionic cordova run ios

Test and share your app on a device with the Ionic View app:
   https://ionicframework.com/products/view

Next Steps:
* Go to your newly created project: cd ./IonicAWS
* Get Ionic DevApp for easy device testing: https://bit.ly/ionic-dev-app

You may have noticed the Ionic Dev App in the above output. If you'd like to learn more about it, please visit the official tutorial.

Create an AWS Account

AWS Free Tier includes offers that expire 12 months following sign up and others that never expire. You can create a free account here: https://aws.amazon.com/free/. The signup is quick and easy:

Image 1

However, please note that you will also need to provide your address and contact information, as well as your credit card. No worries, all the features are free for 12 months and, besides, you can always cancel.

Configure AWS CLI

To configure AWS from the command line, we first need to obtain the access credentials. If you go to your account in AWS and click on the My Security Credentials, you will see instructions screaming at you to create a so-called IAM user:

Image 2

For a more in-depth guide, check the official documentation.

To comply with security requirements, let's create a new user:

Image 3

Choose the Programmatic access:

Image 4

Next, select an appropriate group for your user. As a best practice, do not create credentials of a certain type for a user who will never need that kind of access. For example, for a user who requires access through the AWS Management Console only, do not create access keys.

To be honest, you'll need to do a bit of reading to learn what are all the options here (as they are many). I opted for the PowerUser group, but your use case may vary.

Image 5

This is the final screen where you'll be able to copy the access key and secret:

Image 6

Now, in the console, run aws configure and enter your AWS Access Key ID and AWS Secret Access Key:

aws configure
AWS Access Key ID [None]: AKIAJKQH56VFYCQOYILQ
AWS Secret Access Key [None]: FdKaRaPadjwuy548asfa927
Default region name [None]: 
Default output format [None]:

Setup AWS Mobile Hub

After you created your AWS account and configured the AWS CLI, go to https://aws.amazon.com/mobile/ and click the yellow button on the top right called Sign In to the Console.

In the Mobile Hub dashboard, click the Import your project button:

Image 7

Next, find the mobile-hub-project.zip included in this starter project, and drag and drop it to the import modal.

Image 8

Set the name of the project, make sure you check the Allow AWS Mobile Hub to administer resources on my behalf checkbox and then click Import project.

Once the project is imported, you'll be directed to the dashboard for this Mobile Hub project.

To continue configuring the app, you'll need to find the name of the Amazon S3 bucket auto-generated through the App Content Delivery system. To do this, click the Resources button on the right side of the Mobile Hub project dashboard, find the Amazon S3 Buckets card, and then copy the bucket name that contains hosting-mobilehub:

Image 9

Next, in the terminal, in the IonicAWS folder, run:

aws s3 cp s3://BUCKET_NAME/aws-config.js src/assets

Replacing BUCKET_NAME with the full name of the S3 bucket found above. In my example, it would look like this:

aws s3 cp s3://ionicaws-hosting-mobilehub-1643446370/aws-config.js src/assets

This will copy the auto-generated aws-config.js file into the src/assets folder in your Ionic app, which pre-configures all your AWS settings automatically.

Enabling File Uploads

The demo app has an example of taking a photo or uploading a file to the userfiles S3 bucket. To enable uploads from the web, we have to edit the CORS Policy for the S3 bucket. To do that, open the bucket with userfiles:

Image 10

and select the CORS configuration option:

Image 11

A working, albeit liberal CORS configuration looks like:

XML
<!-- Sample policy -->
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Running the App

Now the app is configured and wired up to the AWS Mobile Hub and AWS services. To run the app in the browser, run:

ionic serve

You should see an output like this:

Starting app-scripts server: --address 0.0.0.0 --port 8100 
--livereload-port 35729 --dev-logger-port 53703 --nobrowser - 
Ctrl+C to cancel
[11:12:04]  watch started ... 
[11:12:04]  build dev started ... 
[11:12:04]  clean started ... 
[11:12:04]  clean finished in 1 ms 
[11:12:04]  copy started ... 
[11:12:04]  deeplinks started ... 
[11:12:04]  deeplinks finished in 49 ms 
[11:12:04]  transpile started ... 
[11:12:07]  transpile finished in 2.39 s 
[11:12:07]  preprocess started ... 
[11:12:07]  preprocess finished in less than 1 ms 
[11:12:07]  webpack started ... 
[11:12:07]  copy finished in 3.11 s 
[11:12:11]  webpack finished in 4.74 s 
[11:12:11]  sass started ... 
[11:12:12]  sass finished in 953 ms 
[11:12:12]  postprocess started ... 
[11:12:12]  postprocess finished in 6 ms 
[11:12:12]  lint started ... 
[11:12:12]  build dev finished in 8.20 s 
[11:12:12]  watch ready in 8.24 s 
[11:12:12]  dev server running: http://localhost:8100/ 

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.1.20:8100
     DevApp: IonicAWS@8100 on Nikolas-MBP

[11:12:15]  tslint: src/providers/user.ts, line: 10 
            'aws_user_pools_web_client_id' is declared but never used. 

       L9:  declare const aws_user_pools_id;
      L10:  declare const aws_user_pools_web_client_id;

[11:12:15]  lint finished in 2.49 s 

Your browser should open up, and you should see the following:

Image 12

If you go and create an account, you will also have to enter the confirmation code sent to the provided email address:

Image 13

The app, with a few tasks added now, should look like this:

Image 14

In the Settings->Account, you can also change your profile picture:

Image 15

Hosting the App on Amazon S3

Since our Ionic app is just a web app, it can be hosted as a static website in an Amazon S3 bucket. To do this, copy the web assets to the S3 bucket:

npm run build
aws s3 cp --recursive ./www s3://ionicaws-hosting-mobilehub-1643446370 

You can find a link to your app in your dashboard under the Endpoint:

Image 16

In my case, the app is now live at http://ionicaws-hosting-mobilehub-1643446370.s3-website-us-east-1.amazonaws.com/.

If you have a lot of data that you need to sync to S3, check out this tutorial.

Conclusion

In this tutorial, we've learned how to easily create a starter project with Ionic framework that's wired to AWS Mobile Hub.

History

  • 26th December, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)