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 a startup

Let me start off by saying there is no right way to start a startup. Also, you shouldn’t blindly follow another startup’s path to success for it’s impossible and everyone’s journey will be unique in their own way.

Every successful startup solves a problem that whose solution adds value to people’s lives. Here are some ways successful startups have come up with solutions to problems in our lives.

Scratch your own itch

In 2013 Ryan Hoover had a genuine interest in finding out about all the cool startups and products that were out on the market. To satisfy his need, he founded a small website called Product Hunt where companies, mostly from the Bay Area, would promote their products. Little did Ryan know, other people were also interested in finding out about up-and-coming startups and soon Product Hunt garnered a lot of traffic from the Bay Area. Fast forward a handful of years, Product Hunt is now the premier place to promote and post about your product or service. In recent years, the traffic from the Bay Area now makes up less than 1.5% of all traffic due to the boom in worldwide popularity. When Ryan started Product Hunt, he did not imagine he would be selling his business for millions of dollars – he was scratching his own itch.

For more information on how Product Hunt came to be listen to Episode “How Product Hunt’s Ryan Hoover Built a $20M Community From Scratch” of Shaan Puri & Ishan Haque podcast “My First Million“.

Create your market

Markets can be created through fear or fear of missing out. On example of such is Brooklinen, a bed sheets startup self dubbed “The Internet’s Favorite Sheets”. For a time on the New York subways, this startup posted ads that implied the average New Yorker’s bedsheets are covered in millions of bacteria since they rarely change them and that our bedsheets are low quality fabrics. As I read this ad, I thought to myself, “Man, do I sleep in a pile of bacteria every night? When’s the last time I bought new bed sheets? When’s the last time I washed my bed sheets?”. Ads like this make you think – maybe think just enough to make a purchase with a strategically place discount coupon upon landing on their website.

Yes, their product may be amazing, however, there are other bed sheets out there with the same or better quality. The only difference here is the clean website, modern looking product, and very well targeted marketing messages. If you never saw that ad then those thoughts would probably not cross your mind.

Brick through the window advertisement
Creating a need in the market with a brick

Solve an old problem in a revolutionary way

Fortunate for us, old problems are still being solved in revolutionary ways due to advances in technology. An age old problem that has been solved countless times is how to get a person from point A to point B. The human race has engineered cars, trains, planes, cruise ships with amusement parks on them, etc. With so many modes of transportation this problem seems beat to a pulp.

Enter Uber, Lyft, and Turo! All of these services have all solved this problem in ways that have never been solved before and are now reaping the benefits tenfold. Instead of hailing down a taxi in the rain on Broadway, I can lay in bed and command an Uber or Lyft driver to meet me outside whenever I want. Yes, I’m still getting from point A to point B, however, it feels like I’m getting personally catered as if I’m royalty. In fact, we have become so spoiled that if an Uber/Lyft driver takes a minute too long to arrive, we millennials become slightly agitated. Can you even fathom a world without a service like Uber/Lyft?

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.

Deploy an Angular app on S3 in 5 minutes

In this post I’ll be showing you how to deploy an Angular application to AWS S3. This post assumes that you already have an AWS account.

Advantages of hosting you Angular application on S3:

  • Cheap
  • Almost no maintenance
  • Easy to deploy

Step 1 – Create a new Angular app

Install the Angular command line interface

npm install -g @angular/cli

Create a new Angular app with the cli

ng new my-app

You can click “Enter” twice in the console to not include Angular Routing and include CSS in the newly generated Angular app on your local machine.

angular create new app command
ng new my-app

With a fresh new Angular app ready to go, it’s time to build the static production bundle.

Step 2 – Build the app

Build the production bundle of the application

ng build --prod

This will generate a dist/ folder, as specified in angular.json in the root directory of your project like so.

Angular build production bundle command line interface
ng build –prod

Once the build process is done you will the generated static files where index.html will be the entry point of the app.

Angular production build

Step 3 – Deploy to S3

In your AWS S3 console, create a new bucket to host your web application and make sure you uncheck “Block all public access” during the “Configure Options” step in the creation process.

Once the bucket is created, drag and drop all the files of the my-app folder that resides inside the dist folder into your S3 bucket. When setting the S3 permissions, select “Grant public read access to this object(s)” as seen below.

set S3 permissions
set S3 permissions

Click “next” through the other options and then AWS will upload your static files to the S3 bucket.

files deployed to S3
files deployed to S3

Lastly, we now hove to tell S3 to serve index.html as the starting point of our application. Navigate to the bucket properties and turn on static website hosting. Set index.html as the entry point of the application and save the configuration. Once you save the configuration click the “Endpoint” link and you will see your hosted Angular app live on the web! Congrats!

static web hosting configuration on S3
static web hosting configuration on S3

Do you need more granular control of how you host your Angular app? Check out my other post on how you can create you own custom configuration with EC2 and Nginx to deploy your Angular app.

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.

Installing WordPress on top of your Angular App

The problem

When companies decided to build their core application with modern Javascript libraries and frameworks such as React, Vue.js or Angular, they do so because of their native feel and amazing user experience. As the application scales and the proof of concept is achieved, more time and money will be invested in marketing and improving SEO.

Soon the marking team will want to run their own experiments to try and increase the conversion rate and test other campaigns. Now the marketing team will flood the engineering teams backlog with marketing related tasks such as updating blog posts, changing images, user flow tracking integrations, etc. This will exponentially slow down the rate of development on business objectives. So how do you give the marketing team their freedom and clear up the engineering back log?

The solution

Give the people what they want! A solution I’ve used a few times now is to install and and configure WordPress to take care of the static pages of the website. As you probably already know WordPress ships with a great admin user interface where almost anyone and log in and alter the static parts of the website with little or no technical experience. With a WordPress admin interface, the marketing team won’t have to bother the engineers with tasks that could disrupt their focus.

NOTE: There are plenty of other great content management systems out there that will do the job.

I’ve shared the nignx configuration below that I’ve used to direct traffic to the right code base depending on the requested route. I serve the WordPress pages from the http://www.my-app.com/ base directory and the Angular application from a sub-directory http://www.my-app.com/app/.

server {

    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/wordpress;
    index index.html index.php;

    server_name www.my-app.com; 
    server_tokens off; 

    error_log /var/log/nginx/error.log; 
    access_log /var/log/nginx/access.log; 

    ##########################
    #### WordPress Routes ####
    ##########################

    location = / {
        # WordPress site log files
        error_log /var/log/nginx/wordpress-error.log; 
        access_log /var/log/nginx/wordpress-access.log; 
        try_files $uri $uri/ /index.php?$args;
    }

    # Other WordPress routes ...

    location ~ .php$ {
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        include fastcgi_params;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        access_log off;
        log_not_found off;
    }

    # robots.txt fallback to index.php
    location = /robots.txt {
        # Some WordPress plugins gererate robots.txt file
        allow all;
        try_files $uri $uri/ /index.php?$args @robots;
        access_log off;
        log_not_found off;
    } 

    # additional fallback if robots.txt doesn't exist
    location @robots {
        return 200 "User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n";
    }

    # Deny all attempts to access hidden files such as
    #.htaccess, .htpasswd, .DS_Store (Mac) excepted
    # .well-known directory. Keep logging the requests 
    # to parse later (or to pass to firewall
    # utilities such as fail2ban)
    location ~ /.(?!well-known\/) {
        deny all;
    }

    # Deny access to any files with a .php extension 
    # in the uploads directory for the single site
    location /wp-content/uploads {
        location ~ .php$ {
            deny all; 
        }
    }

    # Deny access to any files with a .php extension
    # in the uploads directory
    # Works in sub-directory installs and also in 
    # multisite network
    # Keep logging the requests to parse later 
    # (or to pass to firewall utilities such as fail2ban)
    location ~* /(?:uploads|files)/.*.php$ { 
        deny all; 
    } 


    ##########################
    ####  Angular Routes  ####
    ##########################

    location ^~/app/ {
        # User Portal log files
        error_log /var/log/nginx/portal-error.log;
        access_log /var/log/nginx/portal-access.log;
        alias /var/www/dist/my-angular-bundle/;
        try_files $uri$args $uri$args/ /index.html =404;
    }
}

Comment if you have any questions!

Local WordPress Development with Vagrant

The purpose of this post is to show you how to set up an isolated WordPress development environment on your local machine with Vagrant. The benefits of using Vagrant for development is that all your dependencies/packages are installed in an isolated, reproducible, & disposable development environment that doesn’t effect your local machine.

Learn more about what Vagrant is here.

This tutorial assumes that you have both Vagrant and Virtual Box install on your local machine. If not here are the links to both:

  1. https://www.vagrantup.com/
  2. https://www.virtualbox.org/

Once both are installed you will be able to complete the rest of this tutorial.

Step 1 – Fetch WordPress Source Code

Clone the latest WordPress source code from their Github:

git clone https://github.com/WordPress/WordPress.git
Terminal

When git is done fetching the source code you should have a new WordPress folder in your working directory which contains all the WordPress source code files.

Step 2 – Create a Vagrantfile

Run the vagrant init command to generate a new Vagrantfile in the same directory as you cloned the WordPress source code.

Terminal

The Vagrantfile generated tells VirtualBox how to provision and run the Ubuntu virtual machine we will spin up. We’ll edit this in a bit.

For a bit of house cleaning, let’s create a parent folder called wp and put both the WordPress source code and Vagrantfile inside it.

mkdir wp
Code directory

Step 3 – Quick Configuration Changes

Configure the Vagrantfile

Open the wp folder with your favorite text editor and edit the Vagrantfile to look like the following:


Vagrant.configure("2") do |config|
# The base disk image will be Ubuntu 16.04 LTS
config.vm.box = "ubuntu/xenial64"

# Set the host name of the machine
config.vm.hostname = "wordpress"

# A friendly message to appear on machine start up
config.vm.post_up_message = "Welcome to WordPress mate!"

# The private IP to access the virtual machine on your local
config.vm.network "private_network", ip: "192.168.33.10"

# Syncs the shared folder WordPress source code to
# /var/www/Wordpress on the virtual machine
config.vm.synced_folder "Wordpress", "/var/www/Wordpress"

# On start up the machine will run these commands to install
# Nginx
# PHP 7.0 packages we need to run WordPress
config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y nginx
apt-get install -y php7.0 php7.0-common php7.0-mbstring php7.0-gd php7.0-intl php7.0-xml php7.0-mysql php7.0-mcrypt php7.0-fpm
SHELL
end

Configure WordPress

  1. In the WordPress source code folder rename the wp-config-sample.php to wp-config.php.
  2. In the wp-config.php update the salts with salts generate from this website https://api.wordpress.org/secret-key/1.1/salt/
  3. Update define( 'DB_NAME', 'database_name_here' ); with whatever name you want your database to be
  4. Update define( 'DB_USER', 'username_here' ); to be define( 'DB_USER', 'root' );
  5. Update define( 'DB_PASSWORD', 'password ); to be define( 'DB_PASSWORD', 'root' );
Wordpress configuration file

NOTE: For live environments I would highly recommend not using the root user for MySQL nor such a simple password.

Step 4 – Enter the Machine

With these configurations done it’s time to start your virtual machine with vargant up. When the machine is done provisioning and installing all dependencies you’ll see your friendly message in the terminal.

Terminal

To check that everything is working so far navigate to http://192.168.33.10/ on your local machine. You should see the default Nginx page.

Nginx default page

Congratulations, you now have a high performance web server running on your local machine! Just a few more steps to go.

Step 5 – Install MySQL

ssh into your machine with vagrant ssh and install MySQL on your virtual machine with

sudo apt-get install -y mysql-server

After which you will be prompted to enter and reconfirm a password. Above we made out database password root so we will use that input for both prompts.

MySQL Password Prompt
MySQL Confirm Password Prompt

Now we will create our database with the same name as specified in our wp-config.php file. Mine was called wp_db. From inside the machine log into your MySQL instance as the root user with:

mysql -u root -p

Once in the MySQL command line, create your database with:

CREATE DATABASE wp_db;

And then exit the MySQL command line with:

\q
Terminal of virtual machine

Step 6 – Configure Nginx

In your virtual machine, create a wordpress file in /etc/nginx/sites-available with the following contents:

server {
listen 80;
root /var/www/Wordpress;
index index.php index.html;
server_name example.com;

location / {
try_files $uri $uri/ =404;
}

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

location ~ /\.ht {
deny all;
}
}

Remove the default file from /etc/nginx/sites-enabled and symlink the wordpress file you created in the sites-available directory to sites-enabled

Terminal of virtual machine

Confirm that your Nginx configuration is valid with:

sudo nginx -t

Restart your Nginx web server

sudo nginx -s reload

You’re Done!

Reload http://192.168.33.10 and you should WordPress!

Wordpress settings page

Please let me know how I can improve this post and I’ll be happy to update it!