angular pwa: how to implement pwa for angular application

hieunh1801

Nguyễn Hữu Hiếu

Posted on December 30, 2021

angular pwa: how to implement pwa for angular application

References

Implement PWA for Angular Application

  • Step 1: Create angular project
  • Step 2: Make it pwa
  • Step 3: Run and Test your website
  • Step 4: Create your own bussiness login with PwaService
    • Force Update
    • Create your own install pattern

Step 1: Create angular project

ng new angular-pwa-demo
Enter fullscreen mode Exit fullscreen mode

Step 2: Make it pwa

ng add @angular/pwa
Enter fullscreen mode Exit fullscreen mode

Step 3: Run and test your website

# build
npm run build 

# serving your web
# npm install -g http-server
http-server -p 8080 -c-1 dist/angular-pwa-demo -o

Enter fullscreen mode Exit fullscreen mode

Warning: For some reason I don't know why, but trust me, you can avoid so much wasting time asking Google =))

  • You can see it on
  • http://127.0.0.1:8080 # work => remember to use this
  • http://192.168.1.17:8080 # not work
  • http://172.17.0.1:8080 # not work

Step 4: Create your own bussiness login with PwaService

import { HostListener, Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class PwaService {
  readyInstall$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  installed$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  deferredPrompt: any = null;

  constructor(private swUpdate: SwUpdate) {
    // force update
    this.swUpdate.available.subscribe((event) => {
      window.location.reload();
    });

    window.addEventListener(
      'beforeinstallprompt',
      this.onBeforeInstallPrompt.bind(this)
    );
    window.addEventListener('appinstalled', this.onAppInstalled.bind(this));
  }

  onBeforeInstallPrompt(event: any): void {
    console.log('🚀 onBeforeInstallPrompt');
    // Prevent the mini-info bar from appearing on mobile
    event?.preventDefault();
    // Stash the event so it can be triggered later.
    this.deferredPrompt = event;
    this.readyInstall$?.next(true);
  }

  onAppInstalled(event: any): void {
    console.log('🚀 onAppInstalled');
    this.deferredPrompt = null;
    this.installed$.next(true);
  }

  async install() {
    const promptEvent = this.deferredPrompt;
    console.log('install', promptEvent);
    if (!promptEvent) {
      return;
    }
    promptEvent.prompt();

    const result: boolean = await promptEvent.userChoice;
    console.log(result);
    if (result) {
      this.deferredPrompt = null;
      this.readyInstall$.next(false);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
hieunh1801
Nguyễn Hữu Hiếu

Posted on December 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related