How do you read the version hash of the current PWA in Angular?

Viewed 366

I'd like to be able to read the currently active hash of my Angular PWA. However I can't see any mechanism for doing that.

The SwUpdate object provides observables that allow you to read the current version's hash when a new version is activated or when it becomes available but doesn't seem to expose any static method for getting the hash of the current version.

class SwUpdate {
  available: Observable<UpdateAvailableEvent>
  activated: Observable<UpdateActivatedEvent>
  unrecoverable: Observable<UnrecoverableStateEvent>
  isEnabled: boolean
  checkForUpdate(): Promise<void>
  activateUpdate(): Promise<void>
}

I'd like to be able to read something like SwUpdate.current to read the current hash value (say a518f9f1ab65954c2eafa02fec134fa54b391651) without having to wait for an available or activated event. Is this possible?

1 Answers

You can use SwUpdate from @angular/service-worker to do that. For example, you can check that on app.component.ts like this:

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

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

  constructor(private swUpdate: SwUpdate) {}

  checkForUpdate() {
    if (this.swUpdate.isEnabled) {
      this.swUpdate.available.subscribe((event) => {
        console.log('Update is available!');
        console.log('Current version: ' + event.current.hash);
        console.log('New available version: ' + event.available.hash);
      });
    }
  }

  ngOnInit() {
    this.checkForUpdate();
  }
}

Related