Building the PWA logic

Author: Damian Gemza

-

Building the application logic

Finally, the time has come for us to take up something more interesting. It's high time that we complement our template with the logic that is needed for our PWA to work. To do this, copy the following code to the app.component.ts file.


        import { SwUpdate } from '@angular/service-worker';
        import { Component, ViewChild, OnInit } from '@angular/core';
        import { ModalDirective } from 'angular-bootstrap-md';

        @Component({
            selector: 'app-root',
            templateUrl: './app.component.html',
            styleUrls: ['./app.component.scss']
        })
        export class AppComponent implements OnInit {
            @ViewChild('basicModal') basicModal: ModalDirective;

            constructor(private swUpdate: SwUpdate) { }

            ngOnInit() {
                this.checkForUpdates();
            }

            forceUpdate() {
                this.swUpdate.activateUpdate().then(() => {
                document.location.reload();
                });
            }

            checkForUpdates() {
                if (this.swUpdate.isEnabled) {
                    this.swUpdate.available.subscribe(() => {
                    console.log('New Version');
                    this.basicModal.show();
                        });
                    }
                }
            }
      

We inject the SwUpdate service into the constructor, which is a Service Worker used for working with application updates.

During the ngOnInit lifecycle the checkForUpdates() method is called, whose task is to check if a new version of the PWA application is available.

If available, the show() method from the ModalDirective directive is called, which is responsible for displaying the modal with information that a new version of the application is available.
There are two buttons in this modal. One of them is responsible for calling the forceUpdate() method, which reloads the application. The second button closes the modal without updating the application.

It's very simple - isn't it? Service Worker checks if there is a new version based on the application size. If there is one, the user can either reload the application or work with an older version of the application.


Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Damian Gemza
Damian is a front-end developer. He is passionate about everything related to the world of Web Development. He is interested in the subject matter of Angular and everything that is connected with it. He knows and uses the Ionic framework and Progressive Web Apps technology. Recently he has started to write tutorials related to the Web Development.