Dylan  Iqbal

Dylan Iqbal

1560822919

Ionic 4 and Angular 7 Tutorial: HTTP Interceptor Example

The comprehensive step by step tutorial on using HTTP Interceptor with Ionic 4 and Angular 7 including a complete example of authentication or login. We will stick Authentication Token to Angular 7 interceptor. So, you don’t have to repeat calling token when call or consume RESTful API. For the RESTful API, we will use our existing Node, Express, Passport and MongoDB that you can get from our GitHub.

Table of Contents:

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
4.3.1

1. Create a new Ionic 4 and Angular 7 App

To create a new Ionic 4 and Angular 7 application, type this command in your terminal.

ionic start ionic4-angular7-interceptor blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Integrate your new app with Cordova to target native iOS and Android? (y/N) N

After installing NPM modules and dependencies, you will see this question, just type N because we are not using it yet.

Install the free Ionic Pro SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-angular7-interceptor

As usual, run the Ionic 4 and Angular 7 app for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 and Angular 7 app with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

2. Create a custom Angular 7 HttpInterceptor

Before creating a custom Angular 7 HttpInterceptor, create a folder under app folder.

mkdir src/app/interceptors

Next, create a file for the custom Angular 7 HttpInterceptor.

touch src/app/interceptors/token.interceptor.ts

Open and edit that file the add this imports.

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import {
  Router
} from '@angular/router';
import { ToastController } from '@ionic/angular';

Create a class that implementing HttpInterceptor method.

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

}

Inject the required module to the constructor inside the class.

constructor(private router: Router,
  public toastController: ToastController) {}

Implement a custom Interceptor function.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

&nbsp; const token = localStorage.getItem('token');

&nbsp; if (token) {
&nbsp; &nbsp; request = request.clone({
&nbsp; &nbsp; &nbsp; setHeaders: {
&nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': token
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; });
&nbsp; }

&nbsp; if (!request.headers.has('Content-Type')) {
&nbsp; &nbsp; request = request.clone({
&nbsp; &nbsp; &nbsp; setHeaders: {
&nbsp; &nbsp; &nbsp; &nbsp; 'content-type': 'application/json'
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; });
&nbsp; }

&nbsp; request = request.clone({
&nbsp; &nbsp; headers: request.headers.set('Accept', 'application/json')
&nbsp; });

&nbsp; return next.handle(request).pipe(
&nbsp; &nbsp; map((event: HttpEvent<any>) => {
&nbsp; &nbsp; &nbsp; if (event instanceof HttpResponse) {
&nbsp; &nbsp; &nbsp; &nbsp; console.log('event--->>>', event);
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; return event;
&nbsp; &nbsp; }),
&nbsp; &nbsp; catchError((error: HttpErrorResponse) => {
&nbsp; &nbsp; &nbsp; if (error.status === 401) {
&nbsp; &nbsp; &nbsp; &nbsp; if (error.error.success === false) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.presentToast('Login failed');
&nbsp; &nbsp; &nbsp; &nbsp; } else {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; return throwError(error);
&nbsp; &nbsp; }));
}

Add function for call a toast controller.

async presentToast(msg) {
&nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; message: msg,
&nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; position: 'top'
&nbsp; });
&nbsp; toast.present();
}

Next, we have to register this custom HttpInterceptor and HttpClientModule. Open and edit src/app/app.module.ts then add this imports.

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { TokenInterceptor } from './inteceptors/token.interceptor';

Add those modules to the provider array of the @NgModule.

providers: [
&nbsp; StatusBar,
&nbsp; SplashScreen,
&nbsp; { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
&nbsp; {
&nbsp; &nbsp; provide: HTTP_INTERCEPTORS,
&nbsp; &nbsp; useClass: TokenInterceptor,
&nbsp; &nbsp; multi: true
&nbsp; }
],

Now, the HTTP interceptor is ready to intercept any request to the API.

3. Create Ionic 4 Angular 7 Authentication and Book Services

First, create a folder for those services under src/app/.

mkdir src/app/services

Create services or providers for authentication and book.

ionic g service services/auth
ionic g service services/book

Next, open and edit src/app/services/auth.service.ts then replace all codes with this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
&nbsp; providedIn: 'root'
})
export class AuthService {

&nbsp; apiUrl = 'http://localhost:3000/api/';

&nbsp; constructor(private http: HttpClient) { }

&nbsp; login (data): Observable<any> {
&nbsp; &nbsp; return this.http.post<any>(this.apiUrl + 'signin', data)
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('login')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('login', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; logout (): Observable<any> {
&nbsp; &nbsp; return this.http.get<any>(this.apiUrl + 'signout')
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('logout')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('logout', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; register (data): Observable<any> {
&nbsp; &nbsp; return this.http.post<any>(this.apiUrl + 'signup', data)
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('login')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('login', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; private handleError<T> (operation = 'operation', result?: T) {
&nbsp; &nbsp; return (error: any): Observable<T> => {

&nbsp; &nbsp; &nbsp; // TODO: send the error to remote logging infrastructure
&nbsp; &nbsp; &nbsp; console.error(error); // log to console instead

&nbsp; &nbsp; &nbsp; // TODO: better job of transforming error for user consumption
&nbsp; &nbsp; &nbsp; this.log(`${operation} failed: ${error.message}`);

&nbsp; &nbsp; &nbsp; // Let the app keep running by returning an empty result.
&nbsp; &nbsp; &nbsp; return of(result as T);
&nbsp; &nbsp; };
&nbsp; }

&nbsp; /** Log a HeroService message with the MessageService */
&nbsp; private log(message: string) {
&nbsp; &nbsp; console.log(message);
&nbsp; }
}

Next, open and edit src/app/services/book.service then replace all codes with this.

import { Injectable } from '@angular/core';
import { Book } from '../book/book';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
&nbsp; providedIn: 'root'
})
export class BookService {

&nbsp; apiUrl = 'http://localhost:3000/api/';

&nbsp; constructor(private http: HttpClient) { }

&nbsp; getBooks (): Observable<Book[]> {
&nbsp; &nbsp; return this.http.get<Book[]>(this.apiUrl + 'book')
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('fetched books')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('getBooks', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; private handleError<T> (operation = 'operation', result?: T) {
&nbsp; &nbsp; return (error: any): Observable<T> => {

&nbsp; &nbsp; &nbsp; // TODO: send the error to remote logging infrastructure
&nbsp; &nbsp; &nbsp; console.error(error); // log to console instead

&nbsp; &nbsp; &nbsp; // TODO: better job of transforming error for user consumption
&nbsp; &nbsp; &nbsp; this.log(`${operation} failed: ${error.message}`);

&nbsp; &nbsp; &nbsp; // Let the app keep running by returning an empty result.
&nbsp; &nbsp; &nbsp; return of(result as T);
&nbsp; &nbsp; };
&nbsp; }

&nbsp; /** Log a HeroService message with the MessageService */
&nbsp; private log(message: string) {
&nbsp; &nbsp; console.log(message);
&nbsp; }
}

4. Create an Ionic 4 and Angular 7 Book Page

Type this command to generate an Ionic 4 and Angular 7 page for the book.

ionic g page book

Create a Typescript file for handle Book object or as a model for Book object.

touch src/app/book/book.ts

Open end edit that file then replaces all codes with this.

export class Book {
&nbsp; _id: number;
&nbsp; isbn: string;
&nbsp; title: string;
&nbsp; author: number;
&nbsp; publisher: Date;
&nbsp; __v: number;
}

Next, open and edit src/app/book/book.page.ts then add this imports.

import { Book } from './book';
import { BookService } from '../services/book.service';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

Inject all required modules to the constructor.

constructor(private bookService: BookService,
&nbsp; private authService: AuthService,
&nbsp; private router: Router) { }

Declare this variable before the constructor.

books: Book[];

Create a function for consuming or get book list from the book service.

getBooks(): void {
&nbsp; this.bookService.getBooks()
&nbsp; &nbsp; .subscribe(books => {
&nbsp; &nbsp; &nbsp; console.log(books);
&nbsp; &nbsp; &nbsp; this.books = books;
&nbsp; &nbsp; });
}

Call this function from ngOnInit.

ngOnInit() {
&nbsp; this.getBooks();
}

Add a function for log out the current session.

logout() {
&nbsp; this.authService.logout()
&nbsp; &nbsp; .subscribe(res => {
&nbsp; &nbsp; &nbsp; console.log(res);
&nbsp; &nbsp; &nbsp; localStorage.removeItem('token');
&nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; });
}

Next, open and edit src/app/book/book.page.html then replace all HTML tags with this.

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-title>List of Books</ion-title>
&nbsp; &nbsp; <ion-buttons slot="end">
&nbsp; &nbsp; &nbsp; <ion-button color="secondary" (click)="logout()">
&nbsp; &nbsp; &nbsp; &nbsp; <ion-icon slot="icon-only" name="exit"></ion-icon>
&nbsp; &nbsp; &nbsp; </ion-button>
&nbsp; &nbsp; </ion-buttons>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <ion-list>
&nbsp; &nbsp; <ion-item *ngFor="let b of books">
&nbsp; &nbsp; &nbsp; <ion-label>{{b.title}}</ion-label>
&nbsp; &nbsp; </ion-item>
&nbsp; </ion-list>
</ion-content>

The book page just shows the list of the book and log out button on the title bar.

5. Create the Ionic 4 and Angular 7 Pages for Login and Register

Before creating that pages, create this folder under src/app.

mkdir src/app/auth

Now, generate the Ionic 4 and Angular 7 pages.

ionic g page auth/login
ionic g page auth/register

Next, open and edit src/app/auth/login/login.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';

@Component({
&nbsp; selector: 'app-login',
&nbsp; templateUrl: './login.page.html',
&nbsp; styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

&nbsp; loginForm: FormGroup;

&nbsp; constructor(private formBuilder: FormBuilder,
&nbsp; &nbsp; private router: Router,
&nbsp; &nbsp; private authService: AuthService,
&nbsp; &nbsp; public toastController: ToastController) { }

&nbsp; ngOnInit() {
&nbsp; &nbsp; this.loginForm = this.formBuilder.group({
&nbsp; &nbsp; &nbsp; 'username' : [null, Validators.required],
&nbsp; &nbsp; &nbsp; 'password' : [null, Validators.required]
&nbsp; &nbsp; });
&nbsp; }

&nbsp; onFormSubmit(form: NgForm) {
&nbsp; &nbsp; this.authService.login(form)
&nbsp; &nbsp; &nbsp; .subscribe(res => {
&nbsp; &nbsp; &nbsp; &nbsp; if (res.token) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; localStorage.setItem('token', res.token);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['book']);
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; }, (err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; }

&nbsp; register() {
&nbsp; &nbsp; this.router.navigate(['register']);
&nbsp; }

&nbsp; async presentToast(msg) {
&nbsp; &nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; &nbsp; message: msg,
&nbsp; &nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; &nbsp; position: 'top'
&nbsp; &nbsp; });
&nbsp; &nbsp; toast.present();
&nbsp; }

}

Next, open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.

<ion-content padding>
&nbsp; <form [formGroup]="loginForm" (ngSubmit)="onFormSubmit(loginForm.value)">
&nbsp; &nbsp; <ion-card>
&nbsp; &nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-card-title>Please, Sign In</ion-card-title>
&nbsp; &nbsp; &nbsp; </ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Username</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="text" formControlName="username"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Password</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="password" formControlName="password"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none" lines="full" padding-top>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button expand="full" size="default" shape="round" color="success" type="submit" [disabled]="!loginForm.valid">Login</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none">
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button type="button" expand="full" size="default" shape="round" color="medium" (click)="register()">Register</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; </ion-card-content>
&nbsp; &nbsp; </ion-card>
&nbsp; </form>
</ion-content>

Next, open and edit src/app/auth/register/register.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController, AlertController } from '@ionic/angular';

@Component({
&nbsp; selector: 'app-register',
&nbsp; templateUrl: './register.page.html',
&nbsp; styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

&nbsp; registerForm: FormGroup;

&nbsp; constructor(private formBuilder: FormBuilder,
&nbsp; &nbsp; private router: Router,
&nbsp; &nbsp; private authService: AuthService,
&nbsp; &nbsp; public toastController: ToastController,
&nbsp; &nbsp; public alertController: AlertController) { }

&nbsp; ngOnInit() {
&nbsp; &nbsp; this.registerForm = this.formBuilder.group({
&nbsp; &nbsp; &nbsp; 'username' : [null, Validators.required],
&nbsp; &nbsp; &nbsp; 'password' : [null, Validators.required]
&nbsp; &nbsp; });
&nbsp; }

&nbsp; onFormSubmit(form: NgForm) {
&nbsp; &nbsp; this.authService.register(form)
&nbsp; &nbsp; &nbsp; .subscribe(_ => {
&nbsp; &nbsp; &nbsp; &nbsp; this.presentAlert('Register Successfully', 'Please login with your new username and password');
&nbsp; &nbsp; &nbsp; }, (err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; }

&nbsp; async presentToast(msg) {
&nbsp; &nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; &nbsp; message: msg,
&nbsp; &nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; &nbsp; position: 'top'
&nbsp; &nbsp; });
&nbsp; &nbsp; toast.present();
&nbsp; }

&nbsp; async presentAlert(header, message) {
&nbsp; &nbsp; const alert = await this.alertController.create({
&nbsp; &nbsp; &nbsp; header: header,
&nbsp; &nbsp; &nbsp; message: message,
&nbsp; &nbsp; &nbsp; buttons: [{
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text: 'OK',
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler: () => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; &nbsp; }]
&nbsp; &nbsp; });

&nbsp; &nbsp; await alert.present();
&nbsp; }

}

Open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-buttons slot="start">
&nbsp; &nbsp; &nbsp; <ion-back-button></ion-back-button>
&nbsp; &nbsp; </ion-buttons>
&nbsp; &nbsp; <ion-title>Register</ion-title>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <form [formGroup]="registerForm" (ngSubmit)="onFormSubmit(registerForm.value)">
&nbsp; &nbsp; <ion-card>
&nbsp; &nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-card-title>Register here</ion-card-title>
&nbsp; &nbsp; &nbsp; </ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Username</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="text" formControlName="username"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Password</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="password" formControlName="password"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none" padding-top>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button expand="full" size="default" shape="round" color="success" type="submit" [disabled]="!registerForm.valid">Register</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; </ion-card-content>
&nbsp; &nbsp; </ion-card>
&nbsp; </form>
</ion-content>

6. Run and Test the Ionic 4 and Angular 7 Authentication App

Before the run the Ionic 4 and Angular 7 app, we should run the RESTful API server first. After you clone our Express.js API, run this command in the terminal.

npm i

Open another Terminal tabs if your MongoDB server not running then type this command to run it.

mongod

Back to Express API, type this command to run it.

nodemon

or

npm start

Next, we have to run the Ionic 4 and Angular 7 app by typing this command.

ionic serve -l

You should see these pages if everything working properly.

That it’s, the Ionic 4 and Angular 7 HttpIntercepter and HttpClient implementation to the Authentication app. You can find the full working source code on our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ion2FullApp ELITE - The Complete Ionic 3 Starter App and save development and design time.

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Become a JavaScript developer - Learn (React, Node,Angular)

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

#angular #ionic

What is GEEK

Buddha Community

Ionic 4 and Angular 7 Tutorial: HTTP Interceptor Example

sujit kumar

1550072364

How to Implement MFS100 Fingerprint sensor scanner in ionic ?

Jack Salvator

Jack Salvator

1608113009

New Angular 7 Features With Example - Info Stans

What is new in New Angular 7? New Angular 7 features have turned out as a powerful release that really brought advancement in the application development structure.

Here, we have listed new Angular 7 features with examples and write the difference between Angular 6 and Angular 7.

  • Bundle Budget
  • Virtual Scrolling
  • Error Handling
  • Documentation Updates
  • Application Performance
  • Native Script
  • CLI Prompts
  • Component in angular 7
  • Drag and Drop
  • Angular Do-Bootstrap

Read more: Angular 7 Features With Example

#angular 7 features #what’s new angular 7 #new angular 7 features #angular 7 features with examples

Dylan  Iqbal

Dylan Iqbal

1560822919

Ionic 4 and Angular 7 Tutorial: HTTP Interceptor Example

The comprehensive step by step tutorial on using HTTP Interceptor with Ionic 4 and Angular 7 including a complete example of authentication or login. We will stick Authentication Token to Angular 7 interceptor. So, you don’t have to repeat calling token when call or consume RESTful API. For the RESTful API, we will use our existing Node, Express, Passport and MongoDB that you can get from our GitHub.

Table of Contents:

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
4.3.1

1. Create a new Ionic 4 and Angular 7 App

To create a new Ionic 4 and Angular 7 application, type this command in your terminal.

ionic start ionic4-angular7-interceptor blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Integrate your new app with Cordova to target native iOS and Android? (y/N) N

After installing NPM modules and dependencies, you will see this question, just type N because we are not using it yet.

Install the free Ionic Pro SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-angular7-interceptor

As usual, run the Ionic 4 and Angular 7 app for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 and Angular 7 app with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

2. Create a custom Angular 7 HttpInterceptor

Before creating a custom Angular 7 HttpInterceptor, create a folder under app folder.

mkdir src/app/interceptors

Next, create a file for the custom Angular 7 HttpInterceptor.

touch src/app/interceptors/token.interceptor.ts

Open and edit that file the add this imports.

import {
&nbsp; HttpRequest,
&nbsp; HttpHandler,
&nbsp; HttpEvent,
&nbsp; HttpInterceptor,
&nbsp; HttpResponse,
&nbsp; HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import {
&nbsp; Router
} from '@angular/router';
import { ToastController } from '@ionic/angular';

Create a class that implementing HttpInterceptor method.

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

}

Inject the required module to the constructor inside the class.

constructor(private router: Router,
&nbsp; public toastController: ToastController) {}

Implement a custom Interceptor function.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

&nbsp; const token = localStorage.getItem('token');

&nbsp; if (token) {
&nbsp; &nbsp; request = request.clone({
&nbsp; &nbsp; &nbsp; setHeaders: {
&nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': token
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; });
&nbsp; }

&nbsp; if (!request.headers.has('Content-Type')) {
&nbsp; &nbsp; request = request.clone({
&nbsp; &nbsp; &nbsp; setHeaders: {
&nbsp; &nbsp; &nbsp; &nbsp; 'content-type': 'application/json'
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; });
&nbsp; }

&nbsp; request = request.clone({
&nbsp; &nbsp; headers: request.headers.set('Accept', 'application/json')
&nbsp; });

&nbsp; return next.handle(request).pipe(
&nbsp; &nbsp; map((event: HttpEvent<any>) => {
&nbsp; &nbsp; &nbsp; if (event instanceof HttpResponse) {
&nbsp; &nbsp; &nbsp; &nbsp; console.log('event--->>>', event);
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; return event;
&nbsp; &nbsp; }),
&nbsp; &nbsp; catchError((error: HttpErrorResponse) => {
&nbsp; &nbsp; &nbsp; if (error.status === 401) {
&nbsp; &nbsp; &nbsp; &nbsp; if (error.error.success === false) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.presentToast('Login failed');
&nbsp; &nbsp; &nbsp; &nbsp; } else {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; return throwError(error);
&nbsp; &nbsp; }));
}

Add function for call a toast controller.

async presentToast(msg) {
&nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; message: msg,
&nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; position: 'top'
&nbsp; });
&nbsp; toast.present();
}

Next, we have to register this custom HttpInterceptor and HttpClientModule. Open and edit src/app/app.module.ts then add this imports.

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { TokenInterceptor } from './inteceptors/token.interceptor';

Add those modules to the provider array of the @NgModule.

providers: [
&nbsp; StatusBar,
&nbsp; SplashScreen,
&nbsp; { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
&nbsp; {
&nbsp; &nbsp; provide: HTTP_INTERCEPTORS,
&nbsp; &nbsp; useClass: TokenInterceptor,
&nbsp; &nbsp; multi: true
&nbsp; }
],

Now, the HTTP interceptor is ready to intercept any request to the API.

3. Create Ionic 4 Angular 7 Authentication and Book Services

First, create a folder for those services under src/app/.

mkdir src/app/services

Create services or providers for authentication and book.

ionic g service services/auth
ionic g service services/book

Next, open and edit src/app/services/auth.service.ts then replace all codes with this.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
&nbsp; providedIn: 'root'
})
export class AuthService {

&nbsp; apiUrl = 'http://localhost:3000/api/';

&nbsp; constructor(private http: HttpClient) { }

&nbsp; login (data): Observable<any> {
&nbsp; &nbsp; return this.http.post<any>(this.apiUrl + 'signin', data)
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('login')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('login', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; logout (): Observable<any> {
&nbsp; &nbsp; return this.http.get<any>(this.apiUrl + 'signout')
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('logout')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('logout', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; register (data): Observable<any> {
&nbsp; &nbsp; return this.http.post<any>(this.apiUrl + 'signup', data)
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('login')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('login', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; private handleError<T> (operation = 'operation', result?: T) {
&nbsp; &nbsp; return (error: any): Observable<T> => {

&nbsp; &nbsp; &nbsp; // TODO: send the error to remote logging infrastructure
&nbsp; &nbsp; &nbsp; console.error(error); // log to console instead

&nbsp; &nbsp; &nbsp; // TODO: better job of transforming error for user consumption
&nbsp; &nbsp; &nbsp; this.log(`${operation} failed: ${error.message}`);

&nbsp; &nbsp; &nbsp; // Let the app keep running by returning an empty result.
&nbsp; &nbsp; &nbsp; return of(result as T);
&nbsp; &nbsp; };
&nbsp; }

&nbsp; /** Log a HeroService message with the MessageService */
&nbsp; private log(message: string) {
&nbsp; &nbsp; console.log(message);
&nbsp; }
}

Next, open and edit src/app/services/book.service then replace all codes with this.

import { Injectable } from '@angular/core';
import { Book } from '../book/book';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
&nbsp; providedIn: 'root'
})
export class BookService {

&nbsp; apiUrl = 'http://localhost:3000/api/';

&nbsp; constructor(private http: HttpClient) { }

&nbsp; getBooks (): Observable<Book[]> {
&nbsp; &nbsp; return this.http.get<Book[]>(this.apiUrl + 'book')
&nbsp; &nbsp; &nbsp; .pipe(
&nbsp; &nbsp; &nbsp; &nbsp; tap(_ => this.log('fetched books')),
&nbsp; &nbsp; &nbsp; &nbsp; catchError(this.handleError('getBooks', []))
&nbsp; &nbsp; &nbsp; );
&nbsp; }

&nbsp; private handleError<T> (operation = 'operation', result?: T) {
&nbsp; &nbsp; return (error: any): Observable<T> => {

&nbsp; &nbsp; &nbsp; // TODO: send the error to remote logging infrastructure
&nbsp; &nbsp; &nbsp; console.error(error); // log to console instead

&nbsp; &nbsp; &nbsp; // TODO: better job of transforming error for user consumption
&nbsp; &nbsp; &nbsp; this.log(`${operation} failed: ${error.message}`);

&nbsp; &nbsp; &nbsp; // Let the app keep running by returning an empty result.
&nbsp; &nbsp; &nbsp; return of(result as T);
&nbsp; &nbsp; };
&nbsp; }

&nbsp; /** Log a HeroService message with the MessageService */
&nbsp; private log(message: string) {
&nbsp; &nbsp; console.log(message);
&nbsp; }
}

4. Create an Ionic 4 and Angular 7 Book Page

Type this command to generate an Ionic 4 and Angular 7 page for the book.

ionic g page book

Create a Typescript file for handle Book object or as a model for Book object.

touch src/app/book/book.ts

Open end edit that file then replaces all codes with this.

export class Book {
&nbsp; _id: number;
&nbsp; isbn: string;
&nbsp; title: string;
&nbsp; author: number;
&nbsp; publisher: Date;
&nbsp; __v: number;
}

Next, open and edit src/app/book/book.page.ts then add this imports.

import { Book } from './book';
import { BookService } from '../services/book.service';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

Inject all required modules to the constructor.

constructor(private bookService: BookService,
&nbsp; private authService: AuthService,
&nbsp; private router: Router) { }

Declare this variable before the constructor.

books: Book[];

Create a function for consuming or get book list from the book service.

getBooks(): void {
&nbsp; this.bookService.getBooks()
&nbsp; &nbsp; .subscribe(books => {
&nbsp; &nbsp; &nbsp; console.log(books);
&nbsp; &nbsp; &nbsp; this.books = books;
&nbsp; &nbsp; });
}

Call this function from ngOnInit.

ngOnInit() {
&nbsp; this.getBooks();
}

Add a function for log out the current session.

logout() {
&nbsp; this.authService.logout()
&nbsp; &nbsp; .subscribe(res => {
&nbsp; &nbsp; &nbsp; console.log(res);
&nbsp; &nbsp; &nbsp; localStorage.removeItem('token');
&nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; });
}

Next, open and edit src/app/book/book.page.html then replace all HTML tags with this.

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-title>List of Books</ion-title>
&nbsp; &nbsp; <ion-buttons slot="end">
&nbsp; &nbsp; &nbsp; <ion-button color="secondary" (click)="logout()">
&nbsp; &nbsp; &nbsp; &nbsp; <ion-icon slot="icon-only" name="exit"></ion-icon>
&nbsp; &nbsp; &nbsp; </ion-button>
&nbsp; &nbsp; </ion-buttons>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <ion-list>
&nbsp; &nbsp; <ion-item *ngFor="let b of books">
&nbsp; &nbsp; &nbsp; <ion-label>{{b.title}}</ion-label>
&nbsp; &nbsp; </ion-item>
&nbsp; </ion-list>
</ion-content>

The book page just shows the list of the book and log out button on the title bar.

5. Create the Ionic 4 and Angular 7 Pages for Login and Register

Before creating that pages, create this folder under src/app.

mkdir src/app/auth

Now, generate the Ionic 4 and Angular 7 pages.

ionic g page auth/login
ionic g page auth/register

Next, open and edit src/app/auth/login/login.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';

@Component({
&nbsp; selector: 'app-login',
&nbsp; templateUrl: './login.page.html',
&nbsp; styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

&nbsp; loginForm: FormGroup;

&nbsp; constructor(private formBuilder: FormBuilder,
&nbsp; &nbsp; private router: Router,
&nbsp; &nbsp; private authService: AuthService,
&nbsp; &nbsp; public toastController: ToastController) { }

&nbsp; ngOnInit() {
&nbsp; &nbsp; this.loginForm = this.formBuilder.group({
&nbsp; &nbsp; &nbsp; 'username' : [null, Validators.required],
&nbsp; &nbsp; &nbsp; 'password' : [null, Validators.required]
&nbsp; &nbsp; });
&nbsp; }

&nbsp; onFormSubmit(form: NgForm) {
&nbsp; &nbsp; this.authService.login(form)
&nbsp; &nbsp; &nbsp; .subscribe(res => {
&nbsp; &nbsp; &nbsp; &nbsp; if (res.token) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; localStorage.setItem('token', res.token);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['book']);
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; }, (err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; }

&nbsp; register() {
&nbsp; &nbsp; this.router.navigate(['register']);
&nbsp; }

&nbsp; async presentToast(msg) {
&nbsp; &nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; &nbsp; message: msg,
&nbsp; &nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; &nbsp; position: 'top'
&nbsp; &nbsp; });
&nbsp; &nbsp; toast.present();
&nbsp; }

}

Next, open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.

<ion-content padding>
&nbsp; <form [formGroup]="loginForm" (ngSubmit)="onFormSubmit(loginForm.value)">
&nbsp; &nbsp; <ion-card>
&nbsp; &nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-card-title>Please, Sign In</ion-card-title>
&nbsp; &nbsp; &nbsp; </ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Username</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="text" formControlName="username"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Password</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="password" formControlName="password"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none" lines="full" padding-top>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button expand="full" size="default" shape="round" color="success" type="submit" [disabled]="!loginForm.valid">Login</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none">
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button type="button" expand="full" size="default" shape="round" color="medium" (click)="register()">Register</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; </ion-card-content>
&nbsp; &nbsp; </ion-card>
&nbsp; </form>
</ion-content>

Next, open and edit src/app/auth/register/register.page.ts then replace all codes with this.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ToastController, AlertController } from '@ionic/angular';

@Component({
&nbsp; selector: 'app-register',
&nbsp; templateUrl: './register.page.html',
&nbsp; styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

&nbsp; registerForm: FormGroup;

&nbsp; constructor(private formBuilder: FormBuilder,
&nbsp; &nbsp; private router: Router,
&nbsp; &nbsp; private authService: AuthService,
&nbsp; &nbsp; public toastController: ToastController,
&nbsp; &nbsp; public alertController: AlertController) { }

&nbsp; ngOnInit() {
&nbsp; &nbsp; this.registerForm = this.formBuilder.group({
&nbsp; &nbsp; &nbsp; 'username' : [null, Validators.required],
&nbsp; &nbsp; &nbsp; 'password' : [null, Validators.required]
&nbsp; &nbsp; });
&nbsp; }

&nbsp; onFormSubmit(form: NgForm) {
&nbsp; &nbsp; this.authService.register(form)
&nbsp; &nbsp; &nbsp; .subscribe(_ => {
&nbsp; &nbsp; &nbsp; &nbsp; this.presentAlert('Register Successfully', 'Please login with your new username and password');
&nbsp; &nbsp; &nbsp; }, (err) => {
&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);
&nbsp; &nbsp; &nbsp; });
&nbsp; }

&nbsp; async presentToast(msg) {
&nbsp; &nbsp; const toast = await this.toastController.create({
&nbsp; &nbsp; &nbsp; message: msg,
&nbsp; &nbsp; &nbsp; duration: 2000,
&nbsp; &nbsp; &nbsp; position: 'top'
&nbsp; &nbsp; });
&nbsp; &nbsp; toast.present();
&nbsp; }

&nbsp; async presentAlert(header, message) {
&nbsp; &nbsp; const alert = await this.alertController.create({
&nbsp; &nbsp; &nbsp; header: header,
&nbsp; &nbsp; &nbsp; message: message,
&nbsp; &nbsp; &nbsp; buttons: [{
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text: 'OK',
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler: () => {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.router.navigate(['login']);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; &nbsp; &nbsp; }]
&nbsp; &nbsp; });

&nbsp; &nbsp; await alert.present();
&nbsp; }

}

Open and edit src/app/auth/login/login.page.html then replace all HTML tags with this.

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-buttons slot="start">
&nbsp; &nbsp; &nbsp; <ion-back-button></ion-back-button>
&nbsp; &nbsp; </ion-buttons>
&nbsp; &nbsp; <ion-title>Register</ion-title>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <form [formGroup]="registerForm" (ngSubmit)="onFormSubmit(registerForm.value)">
&nbsp; &nbsp; <ion-card>
&nbsp; &nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-card-title>Register here</ion-card-title>
&nbsp; &nbsp; &nbsp; </ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Username</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="text" formControlName="username"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-label position="floating">Password</ion-label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-input type="password" formControlName="password"></ion-input>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; &nbsp; <ion-item lines="none" padding-top>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ion-button expand="full" size="default" shape="round" color="success" type="submit" [disabled]="!registerForm.valid">Register</ion-button>
&nbsp; &nbsp; &nbsp; &nbsp; </ion-item>
&nbsp; &nbsp; &nbsp; </ion-card-content>
&nbsp; &nbsp; </ion-card>
&nbsp; </form>
</ion-content>

6. Run and Test the Ionic 4 and Angular 7 Authentication App

Before the run the Ionic 4 and Angular 7 app, we should run the RESTful API server first. After you clone our Express.js API, run this command in the terminal.

npm i

Open another Terminal tabs if your MongoDB server not running then type this command to run it.

mongod

Back to Express API, type this command to run it.

nodemon

or

npm start

Next, we have to run the Ionic 4 and Angular 7 app by typing this command.

ionic serve -l

You should see these pages if everything working properly.

That it’s, the Ionic 4 and Angular 7 HttpIntercepter and HttpClient implementation to the Authentication app. You can find the full working source code on our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ion2FullApp ELITE - The Complete Ionic 3 Starter App and save development and design time.

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Become a JavaScript developer - Learn (React, Node,Angular)

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

#angular #ionic

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Einar  Hintz

Einar Hintz

1594631472

Pros and Cons of Ionic Development

Entrepreneurs around the world want a top-notch mobile application for their business in both Android and iOS platforms. Most of them get stuck mid-way where they struggle to pick the best technology suitable for their business. From questions such as native mobile development or cross-platform development? Flutter or Ionic or React Native?. Each technology and development approach has its own Pros and Cons from which you will need to choose the right one for your business. If you think Ionic is the right cross-platform application development, here are a few pros and cons of Ionic development. 

What is Ionic Framework?

Being an open-source SDK for building Hybrid mobile applications in both Android and iOS platforms, Ionic is the best choice for building top of the line mobile applications. This Ionic framework is completely based on Apache Cordova and Angular. More precisely, Ionic is an npm module that requires the installation of Node JS to function.

One can build a full functioning mobile application in both platforms using their Javascript, HTML, and CSS knowledge without requiring the basics of Kotlin or Java. More than 5 Million mobile applications are built using this Ionic framework by leveraging its platform-specific UI elements, innumerable libraries, and more exciting features.

The applications that are built using the Ionic framework are cross-platform, web-based, and have access to native device’s APIs.

Ionic Applications are

  • Cross-platform – Single code base for both platforms (except native components)
  • Web-based – Built using web-views and can be displayed in a browser like PWAs.
  • Access to native API components – They can access native device’s camera, files, and others.

Advantages of Ionic Development

Quick Development and Time To Market

For entrepreneurs and business owners, ionic development can be beneficial if they want to develop a mobile application in both platforms in a short period of time while comparing to native applications. Building native applications specifically for each platform can be time-consuming which can imply a delay in time to market and development cost of native applications are generally expensive.

#mobile app development #ionic 4 advantages #ionic 4 best practices #ionic 5 #ionic appflow #ionic capacitor pros and cons #ionic vs react native #react native pros and cons #what is ionic app development

Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade