Test your Angular App with a Local Mock API JSON Server

Ever wanted to test your front end will a fully functional fake REST API before connecting it to your actual backend? Well now you can in 30 seconds with this nifty npm package – so let’s get started.

In your Angular app install the json-server.

npm install -D json-server

In package.json include the following json-server command in the "scripts" block:

... 
"scripts": {   
  ...   
  "test": "ng test",    
  "lint": "ng lint",   
  "e2e": "ng e2e",    
  "json-server": "json-server --watch db.json --port 3004"  
}, 
...

Create a db.json file in your root directory with the following contents:

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

Next write a simple GET request to fetch the only "post" object in the database.

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {tap} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get('http://localhost:3004/posts/1')
       .pipe(tap(console.log)).subscribe();
  }
}

Time to serve your Angular app and fake REST API! In two separate terminal windows start your Angular development server and the JSON server.

ng serve
npm run json-server

If you open the console of your Angular app you’ll see that the data was fetched and is ready to use!

fake REST API GET request success
fake REST API GET request success

I highly recommend you look through the official documentation of this package as there’s so much more you can do with this fake REST API tool. Happy prototyping!

How to start using your integrated development environment like a pro

Do you “kind of” know your integrated development environment (IDE)? Do you use your mouse to click between its various functions and copy & paste? Are you spending too much time scrolling through code? If you answered “yes” to any of these questions, then you’re missing out on the true power of your IDE.

After reading “The Pragmatic Programmer” I realized that I was not as proficient with my IDE as I thought I was.

“We think it’s better to know one editor very well, and use it for all editing tasks: code, documentation, memos, system administration, and so on.”


“You need to be proficient. Simply typing linearly and using a mouse to cut and paste is not enough”

“The Pragmatic Programmer” by Andrew Hunt & David Thomas – 82

The simple solution to start your journey of IDE master – don’t use your mouse for any tasks inside the IDE. In the beginning this will be very frustrating. When you find yourself reaching for your mouse, you will have to stop and Google the keyboard shortcut for the task you wish to do.

At the time of this writing I haven’t used a mouse to perform any task while using my IDE for the past two months and I can confidently say I feel much more proficient/effective when I code.

View your Angular local development environment on your phone

In this post I will show you how ngrok has become an invaluable tool for testing responsive designs – especially on mobile phones. It’s probably the easiest local development tunnel I’ve ever used. Let’s get started:

Step 1 – Setup & Installation

Navigate to https://ngrok.com/ and click the “Get started for free” button. Once you create a free account, you’ll find yourself on the dashboard page with a set of small instructions:

ngrok home page
  1. Download the ngrok zip file for your OS
  2. Unzip the file that was just downloaded $ unzip /path/to/ngrok.zip
  3. Connect your account with the token they provide you `$ ./ngrok authtoken your_token_should_be_very_long_3485994389

Step 2 – Serve & Connect

I’m running my local Angular development environment on port 4200. Please change the port number in the following commands if you’re running on a different port.

With your local Angular development server running in the background. Run the following in your terminal:

$ ./ngrok http 4200 -host-header="localhost:4200"

After which your terminal will look like the following which means your local development tunnel has opened.

ngrok terminal

Simply copy and paste the “Forwarding” address into the URL of any phone, tablet, or really anything else you want to view your local development server on and you should see you Angular application!

To quit the local development tunnel run Crtl + C.

Top Visual Studio Code extensions for Angular Development

Below is a list of some VSCode extensions I use heavily when developing Angular web applications that have helped me move faster. Check them out!

Compodoc

This first tool is not a VSCode extension, however, I have been using this lately as an invaluable tool when developing in bigger teams. As a developer you will spend a lot of time reading other people’s code where there may not be any documentation. The good people at Compodoc give you an out-of-the-box solution for automatically generating an entire static site of documentation for your Angular project right in your working directory. By providing some really cool graphical diagrams of all the imports, routes, and modules, understanding other people’s code just got a little easier.

Angular7 Snippets

Having this extension installed provides hot keys and short cuts to generate Angular and Typescript snippets. There’s not much more to be said here.

Prettier

Prettier is my de-facto code formatter and takes care of 80% of all of my code formatting. It’s also extremely customizable in that you can include a .prettierrc file in the root directory of your project and customize exactly how Prettier formats your code. Recently I’ve been turned off by the way it formats HTMLcode blocks so I’ve added a .prettierignore file to the root directory of my project to tell Prettier to ignore formatting my HTML – hence the missing 20%. See some sample files below:

// .prettierrc
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true
}
// .prettierignore
*.html

Code Spell Checker

Anybody writing code should some sort of spell checker in place. If you’re like me misspell words constantly then this extension will help you spot your blunders and correct them before your users read your mistakes in production!

You’ve inherited 100,000 lines of spaghetti code. Now what?

It’s the first day of your job at your startup as the new Angular developer on the block and you spend the first week warming up to the code base. On Friday your founder interrupts your morning coffee to say that he wants you to start working on updating an existing feature. You say “Sure! It’s about time I got my hands dirty”. You roll up your sleeves and get to work only to find:

  • Copy and pasted PHP code snippets in your Angular project
  • heavily using var instead of let or const
  • == instead of === almost everywhere you can find any object comparison
  • Each HTML and TypeScript file pushes ~1200 lines of code
  • Each route is it’s own component – there are no reusable components

And guess what! It’s all yours buddy. Don’t fret! Here’s what you should not do in this situation.

What you shouldn’t do

1. Don’t whine or complain

Do not set up a meeting with your boss and say “Hey this code base is horrible. We have to stop everything and re-do it all”. What are you expecting your founder to say to this? “Hey, wow bob, well…when you put it that way we should stop all product development and refactor the whole thing the way you want it”. Throwing your problems at your boss does not help the business. If you’re going to present a problem, present a solution or at least things you’ve tried. The business isn’t going to stop because you arrived.

2. Don’t be a cowboy

Your inner perfectionist is coming out now and you have the sudden urge to re-write the code base or at least most of it thinking you can do it better. Don’t. What is working now in production is working. There are many months, maybe even years of knowledge and experience behind that code block you just want to tear apart. Document the mysterious code blocks/components so that the next guy who looks at the code has some knowledge to work with. Refactoring the whole code base will be a drain of your company’s resources.

What you should do (from my experience)

1. Communicate constructively

Everything starts with solid communication. You should communicate with your direct report that the code is not in the best condition where you can just start pumping out features but that you’ll do your best to keep up with the deadlines. Don’t torture yourself by keeping the state of the project a secret and burn yourself out to meet a deadline to “just make it work” because you’re still warming up to the code base. This always leads to problems down the line. Work with your product manager to set appropriate deadlines. 

2. Start enforcing standards from day one

Do your best not to contribute to the spaghetti mess that you inherited. Start implementing some coding standards from day one and continue to enforce those standards. This will be very hard in the beginning, however, you will be very happy you did in a few months. You have to start somewhere right?

3. Understand your data services

I’ve found that the most effective way for me to start breaking up my Angular application in to components is to first understand the services that provide data to the components and make them accessible. When I start making my components, I try to make them as independent as possible from the other components. Understanding where your data is coming from and how to inject it properly in each component will help keep your components more independent, maintainable, and reusable.

3. Create your reusable components

Once you know where you data feeds are at, building reusable and maintainable components is a synch. In time you’ll see your code base come together and maybe you won’t be hating your work as much when sprints are easier to complete because you put the ground work to make reusable components.

Final notes

Refactor the code bit by bit on each deployment and soon you will be a much happier camper in about a month. Work hard but don’t forget to work smart. Please drop some comments below on how you guys have dealt with similar situations.

Simple Angular CI/CD pipeline with GitLab & AWS

In this tutorial, I will show you how to set up a simple CI/CD pipeline that compiles code on GitLab and then deploys to AWS EC2 via AWS CodeDeploy. This tutorial assumes:

  1. You have a working EC2 Ubuntu instance set up with a web server such as Nginx or Apache running and configured. 
  2. You have an existing code repository hosting an Angular project on GitLab.

Technologies Used: 

  • Angular 7
  • Gitlab CI/CD
  • AWS S3
  • AWS CodeDeploy
  • AWS EC2 Ubuntu 18.04 LTS

I’ve made a start project that I will be referencing throughout this project on Github will all the files you need already built in. Check it out here!

Step 1 – Create an S3 to AWS CodeDeploy Pipeline

I really don’t like dropping links in tutorials like this, however, for the sake of not re-writing Amazon’s documentation, I will have to tell you to follow all instructions in the tutorial in the link below. Only once you finished the tutorial will you be able to continue with the rest of this tutorial. Once you’re done with Amazon’s tutorial, you will have a CD pipeline ready to go waiting for GitLab to send the code.

https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-simple-s3.html

If you have successfully completed the above tutorial, any changes pushed to your S3 bucket will be deployed immediately to your EC2 instance. Then steps below will show you how to upload your production bundle to S3 from Gitlab to complete the CI/CD pipeline.

Step 2 – Create an appspec.yml 

Welcome back! The first thing we’ll have to do is create an appspec.yml file in the src/ folder of our project. The appspec.yml will tell AWS CodeDeploy to deploy your code in a specific file directory on the server – in our case, it’s the /var/www/ directory. 

version: 0.0
os: linux
files:
  - source: ./
    destination: /var/www/

Then we have to tell angular to include this file as an asset so it stays preserved during the production build. To do this, we edit the assets block in our angular.json file to include "src/appspec.yml":

...
"tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/manifest.json",
              "src/appspec.yml"
            ],
            "styles": [
...

Step 3 – Create .gitlab-ci.yml

Gitlab offers a continuous integration service if you add a

.gitlab-ci.yml

file to the root directory fo your code repository. I’ve provided a sample .gitlab-ci.yml file as seen in example Github project. Please be sure to update the group name and repository name for your own project. If you copy this code please be sure to use your own repository name.

image: node:10

stages:
  - build
  - deploy

build:
  stage: 'build'
  script:
    - apt update
    - apt-get install -y nodejs
    - npm install -y npm@6.11.0
    - nodejs -v
    - npm -v
    - ls -la -F
    - npm ci
    - npx ng build --prod
  cache:
    paths:
      - node_modules/
  artifacts:
    when: on_success
    name: '$CI_JOB_NAME-$CI_COMMIT_REF_NAME'
    paths:
      - dist/angular-gitlab-ci-cd-example/
  only:
    - dev
    - master

deploy:
  stage: 'deploy'
  environment:
    name: production
  script:
    - apt update
    - apt install -y software-properties-common
    - apt install -y python-dev
    - apt install -y python-pip
    - pip install awscli
    - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
    - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
    - aws configure set region us-east-1
    - ls -la -F
    - mv dist/angular-gitlab-ci-cd-example/appspec.yml dist/
    - cd dist
    - ls -al -F
    - cd ..
    - aws deploy push --application-name angular-gitlab-ci-cd-example --s3-location $AWS_S3_LOCATION --ignore-hidden-files --source dist
  only:
    - master

If you commit to your master branch with this file in the root directory of your project, a CI pipeline will initiate with two steps outlined line-by-line below:

The Build Stage

1.Update the packages in the node:10 Docker container

- apt update

2. Install node & npm

- apt-get install -y nodejs
- npm install -y npm@6.11.0
- nodejs -v
- npm -v

3. Run npm install

- npm install

4. Build the production bundle of Angular using the local cli

- npx ng build --prod

6. Tell GitLab to cache your node_modules so that your project builds faster next time around

cache: 
    paths: 
      - node_modules/

7. This code block creates a build artifact that will be passed onto the next stage in the pipeline if all operations in the container run without error. In the case of Angular7, I’m passing the created dist/ directory to the next stage so that GitLab can send it to AWS to be deployed

  artifacts: 
    when: on_success    
    name: "$CI_JOB_NAME-$CI_COMMIT_REF_NAME"
    paths: 
      - dist/angular-gitlab-ci-cd-example/

8. This keyword tells GitLab only to run this stage when a commit is pushed to either the master and dev branches. You can customize any stage to run a specific set of branched or all branches if that’s what you need. 

  only:
    - dev
    - master

The Deploy Stage

1. Update the packages on the node:10 Docker image, install the python libraries needed for AWS CLI and then install the AWS CLI.

script: 
    - apt update
    - apt install -y software-properties-common
    - apt install -y python-dev  
    - apt install -y python-pip
    - pip install awscli

2. Navigate to your CI/CD settings in GitLab and add the following variables for your $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY from the CodeDeploy IAM User you created earlier from following the AWS tutorial in Step 1. You should also include the $AWS_S3_LOCATION as a CI/CD variable as well in the following format:

s3://your-bucket-name/your-bundle-name.zip

The <key> will be by the same name as the zip created from the build stage.

3. In this step, we are configuring the AWS CLI with the IAM Credentials of a user with the correct CodePipeline policies attached.

    - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
    - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
    - aws configure set region us-east-1

4. Remember from step 1 how we made sure the appspec.yml was preserved in the dist/ production bundle? Well, now we have to move it out it to the same directory level as the dist/ folder so that it sits on the same level as the dist/ folder. We have to do this to make the appspec.yml visible to AWS. If we do not do this, the AWS CLI will throw an error stating that it cannot find the appspec.yml file in the next step.

- mv dist/angular-gitlab-ci-cd-example/appspec.yml dist/
- cd dist
- cd .. 

5. Use the AWS CLI to deploy the dist/ bundle to AWS S3

 - aws deploy push --application-name angular-gitlab-ci-cd-example --s3-location $AWS_S3_LOCATION --ignore-hidden-files --source dist
only:
    - master

You’re Done!

Once you push your code to the master branch, navigate to the CI/CD pipeline and watch your code being built. Once GitLab is done building the production bundle, it will send it to AWS S3, which in turn will be deployed onto your live server moments later. I would love to hear your feedback on how I can improve this simple pipeline. 

5 Atom packages that will speed up your workflow

The purpose of this article is to share 5 Atom packages that I use constantly that have sped up my workflow. Let’s start!

atom-beautify

atom-beautify on atom packages

With atom-beautify you never have to worry making sure your code is perfectly indented throughout the entire page. By hitting a designated set of hotkeys this package will take you unformatted code and indent it perfectly as if you spend the next 15 minutes indenting it yourself. The creators of this project made beautifiers for all types of code formats and languages such as JS, ESLint, Nginx, Vue, and many more.

autoclose-html

autoclose-html on atom packages
As you can probably infer from the name of the of the package, autoclose-html will automatically insert the closing HTML tag after you close the opening tag.

emmet

emmet on atom packages

emmet has had the largest impact on speeding up my web development workflow. Generating HTML code blocks has never been easier with the set of hotkey shortcuts this package comes pre-packaged with. For those who use a front-end framework like Bootstrap4 are familiar with writing the following code:

Screen Shot 2018-10-08 at 1.49.39 PM

For some of us, this code becomes muscle memory at some point. However, with emmet we can simply write the following:

div.row>div.col*3

and hit tab on the keyboard and generate the same code above.

emmet hotkey cheat sheet

minimap

minimap on atom packages

minimap generates a map of all the code in your open document/script file where you can quickly navigate to any point in your open source file no time at all. This is a huge step up from using a combination Ctrl + F and memory to jump between lines of code.

platformio-ide-terminal

platformio-ide-terminal on atom packages

This package allows you to open up multiple terminal instances in Atom in your current working directly. This is very convenient since you don’t have to open up another application to access the terminal.