PWA (Progressive Web App) in Angular Application

In this article, we discuss how to add PWA in our application. A few days ago we discuss on whats is a feature of the PWA and why we use.
Let’s create a new project for PWA in angular for that you need to run the following command to create a project.


ng new pwa-demo

“pwa-demo” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd pwa-demo”. To Run angular applications, it required to run “ng serve”.
After that, we need to install the Angular material npm package in our application. run below command to install.


ng add @angular/material

When installing material it asks to theme default or custom theme. For use default, we need to select the default theme. Then it will ask to import browser animation in Angular material. after installing the theme we need to import CSS in style.css


material pink theme in src/styles.css file.


@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Let’s create “material.module.ts” file for material component to import. Below code added in that file.


import { NgModule } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule  } from '@angular/material/paginator';
import { MatToolbarModule  } from '@angular/material/toolbar';


@NgModule({
    imports: [
        MatTableModule,
        MatPaginatorModule,
        MatToolbarModule
    ],
    exports: [
        MatTableModule,
        MatPaginatorModule,
        MatToolbarModule
    ]
})

export class MaterialModule { }

After adding we need to import in the “app.module.ts” file


/* angular material module */
import { MaterialModule } from './material.module';
@NgModule({
.........
  imports: [
MaterialModule 
]
......

Let’s create REST API using HttpClient for getting data from the server. Import the “HttpClientModule” in “app.module.ts” file.


/* angular material module */
import { HttpClientModule } from '@angular/common/http';
@NgModule({
.........
  imports: [
HttpClientModule 
]
......

Let’s create service for the getting data from the server.


ng g service rest-api-server

It’s create service we need to add code below code to get the data.


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

export interface User {
  id: string;
  name: string;
  email: string;
}

@Injectable({
  providedIn: 'root'
})
export class RestApiService {
  api: string = "https://jsonplaceholder.typicode.com/users";

  constructor(private http: HttpClient) {}

   getUsers(): Observable {
    return this.http.get(this.api);
  }
}

Let’s fetch the data from the service then display the data
“app/app.component.ts”


import { Component, ViewChild } from '@angular/core';
import { RestApiService } from './rest-api.service';
import { MatPaginator  } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';

export interface TableElement {
  id: string;
  name: string;
  email: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  Data: TableElement[];
  col: string[] = ['id', 'name', 'email', 'website'];
  dataSource = new MatTableDataSource(this.Data);
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(private restApiService: RestApiService) {
    this.restApiService.getUsers().subscribe((res) => {
      this.dataSource = new MatTableDataSource(res);
      setTimeout(() => {
        this.dataSource.paginator = this.paginator;
      }, 0);
    })
  }

}

“app/app.component.html”


<mat-toolbar color="accent" class="header">
  <span>Angular PWA Example</span>
</mat-toolbar>

<table mat-table [dataSource]="dataSource" matSort>
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> ID. </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <ng-container matColumnDef="email">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Email </th>
    <td mat-cell *matCellDef="let element"> {{element.email}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="col"></tr>
  <tr mat-row *matRowDef="let row; columns: col;"></tr>
</table>

<mat-paginator [pageSizeOptions]="[5,10,20]" showFirstLastButtons></mat-paginator>

Let’s add the PWA in our application For that we need to run the “ng add @angular/pwa” command. It creates/update below files.
1) manifest.webmanifest file genrated.
2) service worker ngsw-config.json file genrated.
3) It generates icons in the assets folder.
4) It updated the index.html file with below code


 <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">

5) In “app.module.ts” file it added below line


import { ServiceWorkerModule } from '@angular/service-worker';
......
 imports: [
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production, registrationStrategy: 'registerImmediately' })
]

After adding the PWA we need to build a production to run on a live server. For that, we need to run the below command.


ng build --prod

after genrated production version go to the “cd dist/pwa-demo”. then run “http-server -o” to display the server output.
Output

Spread the love
  •  
  •  
  •  
  •  
  • 2
  •  
  •  
  •