June 13 2019

Angular 7 Tutorial Part 7 - Migrating to an Angular CLI Project

Other parts available in Angular 7 tutorial series:


Angular 7 Tutorial Part 7

In part 7 of this Angular 7 tutorial series we're going to copy/migrate the example application from a custom webpack project into an Angular CLI project. This part of the series is optional for those of you that prefer to build apps with the Angular CLI rather than directly with webpack, or if you're just interested in seeing how to migrate an Angular webpack app to the Angular CLI.

The complete source code for this part of the tutorial is available on github at https://github.com/cornflourblue/angular-7-tutorial in the part-7 folder. If you haven't completed Part 6 (Home Page & Alert Component) but want to follow the steps in this part of the tutorial series you can start with the code in the part-6 folder of the github repo.

Steps:

  1. Install the Angular 7 CLI
  2. Create a new Angular CLI Project
  3. Copy Angular Tutorial App Code to Angular CLI Project
  4. Copy Config Variables to Environment Configs
  5. Replace 'config.apiUrl' with 'environment.apiUrl' in Services
  6. Start Angular 7 Application!


Install the Angular 7 CLI

Install the Angular 7 CLI globally on your system by running the command npm i -g @angular/cli@7. If you prefer to use the latest version of the cli you can run the command npm i -g @angular/cli.

You can test that the Angular CLI was installed correctly by running the command ng version.


Create a new Angular CLI Project

Create a new Angular CLI project named angular7tutorial by running the command ng new angular7tutorial.

For the option Would you like to add Angular routing? enter N.

For the options Which stylesheet format would you like to use? select whichever you prefer, I usually go with Less.

This will create the project in a new folder named angular7tutorial, I would have preferred to use the hyphenated project name angular-7-tutorial but the CLI doesn't seem to like hyphens.


Copy Angular Tutorial App Code to the Angular CLI Project

Replace the /src/app folder in the new Angular CLI project with the /src/app folder from the tutorial project you created in the previous parts of the tutorial series. If you're starting with this part of the series you can copy the /part-6/src/app folder from the tutorial github repo - https://github.com/cornflourblue/angular-7-tutorial/tree/master/part-6/src/app.

Replace the /src/index.html file in the new Angular CLI project with the /src/index.html file from the tutorial project you created in the previous parts of the tutorial series. If you're starting with this part of the series you can copy the /part-6/src/index.html file from the tutorial github repo - https://github.com/cornflourblue/angular-7-tutorial/tree/master/part-6/src/index.html.


Copy Config Variables to Environment Configs

Angular CLI projects store config data in environment config files (/src/environments/environment.ts & /src/environments/environment.prod.ts) instead of in the webpack.config.js that we've been using so far, so we need to copy the config data from our webpack config to the Angular CLI environment config files.

Copy the following apiUrl property to both environment config files in the Angular CLI project:

apiUrl: 'http://localhost:4000'


Add '@environments' path alias to tsconfig.json

Add the path alias "@environments/*": ["src/environments/*"] to the compilerOptions/paths property in the /tsconfig.json file.

This creates an alias @environments that maps to the /src/environments folder, so the environment config can be imported with the alias (e.g. import { environment } from '@environments/environment';) instead of having to traverse directories with a relative path (e.g. import { environment } from '../../environments/environment';).

This is how the /tsconfig.json file should look after the update, the new lines are 21-23:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@environments/*": ["src/environments/*"]
    }
  }
}


Replace 'config.apiUrl' with 'environment.apiUrl' in Services

We need to update the Angular services that connect to the backend API to get the apiUrl config variable from the Angular CLI environment object instead of the webpack config object.

Update Authentication Service

Update the authentication service (/src/app/_services/authentication.service.ts) to use the new environment config object.

This is how the updated service should look, line 6 has been added and line 23 updated:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { environment } from '@environments/environment';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<any>;
    public currentUser: Observable<any>;

    constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<any>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue() {
        return this.currentUserSubject.value;
    }

    login(username, password) {
        return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                this.currentUserSubject.next(user);
                return user;
            }));
    }

    logout() {
        // remove user from local storage and set current user to null
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
    }
}


Update User Service

Update the user service (/src/app/_services/user.service.ts) to use the new environment config object.

This is how the updated service should look, line 4 has been added and lines 11, 15 and 19 updated:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { environment } from '@environments/environment';

@Injectable({ providedIn: 'root' })
export class UserService {
    constructor(private http: HttpClient) { }

    getAll() {
        return this.http.get<any[]>(`${environment.apiUrl}/users`);
    }

    register(user) {
        return this.http.post(`${environment.apiUrl}/users/register`, user);
    }

    delete(id) {
        return this.http.delete(`${environment.apiUrl}/users/${id}`);
    }
}


Start Angular 7 Application!

Run the command ng serve --open from the project root folder (where the package.json is located) to launch the Angular 7 CLI application.

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by