I used both answers from Carrm and NeNad to create a page in my Angular app to manage updates.
I also used @saithodev/ts-appversion package to manage version.
Later, I create a script to update the app version on each build and show it on that page (appversionupdate.mjs).
Then, in package.json, I set the script to use with npm run.
This way, when I build and deploy the project the version is updated as I want.
I know that the OP has not asked for all this, but it may be useful for the community.
menu.component.html
<mat-toolbar color="accent" fxLayout="row" fxLayoutAlign="space-between center" class="top-bar">
<div fxLayout="row" fxLayoutAlign="start center">
<h1>Atualização do app</h1>
</div>
</mat-toolbar>
<main>
<div>
<h2>Versão do app instalada: {{versao}}</h2>
</div>
<h3>Status da atualização</h3>
<!-- lista sem numeração em HTML -->
<ul>
<li *ngFor="let mensagem of mensagens">
{{mensagem}}
</li>
</ul>
<button mat-raised-button color="accent" (click)="atualizarApp();" class="botao">Atualizar app</button>
</main>
menu.component.ts
import { Component, OnInit } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { versions } from 'src/_versions';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
mensagens: string[] = [];
versao: string = 'Versão ainda não carregada pelo sistema.';
constructor(
private readonly swUpdate: SwUpdate,
) { }
ngOnInit(): void {
this.atualizarApp();
this.versao = versions.version;
}
async atualizarApp() {
this.mensagens?.push(`${this.getFormattedDate()} Iniciando atualização do app.`);
try {
// Check if Service Worker is supported by the Browser
if (this.swUpdate.isEnabled) {
this.mensagens?.push(`${this.getFormattedDate()} Verificado que este navegador suporta a atualização do app.`);
const isNewVersion = await this.swUpdate.checkForUpdate();
this.mensagens?.push(`${this.getFormattedDate()} Verificando se há nova versão a ser baixada.`);
// Check if the new version is available
if (isNewVersion) {
this.mensagens?.push(`${this.getFormattedDate()} Nova versão do app encontrada. Fazendo download.`);
const isNewVersionActivated = await this.swUpdate.activateUpdate();
// Check if the new version is activated and reload the app if it is
if (isNewVersionActivated) {
this.mensagens?.push(`${this.getFormattedDate()} Nova versão baixada e instalada.`);
window.location.reload();
}
} else {
this.mensagens?.push(`${this.getFormattedDate()} O Materiale app já está atualizado.`);
}
} else {
this.mensagens?.push(`${this.getFormattedDate()} Verificado que este navegador não suporta a atualização do app automática e outras funcionalidades.`);
this.mensagens?.push(`${this.getFormattedDate()} Por favor, atualize o navegador para a versão mais recente. Baixe preferencialmente o Google Chrome.`);
}
} catch (error) {
this.mensagens?.push(`${this.getFormattedDate()} Houve algum error ao tentar atualizar o app. Mensagem de erro: ${error}`);
this.mensagens?.push(`${this.getFormattedDate()} É possível que este navegador não seja compatível. Por favor, atualize o navegador para a versão mais recente. Baixe preferencialmente o Google Chrome.`);
this.mensagens?.push(`${this.getFormattedDate()} Mensagem de erro: ${error}`);
//window.location.reload();
}
}
getFormattedDate(): string {
var date = new Date();
var str = `${date.getDate()}/${(date.getMonth() + 1)}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
return str;
}
}
appversionupdate.mjs
import fs from 'fs';
//console.log("Atualizado versao do app");
var obj = JSON.parse(fs.readFileSync('package.json', 'utf8'));
var version = obj.version;
var major = version.split('.')[0];
var minor = version.split('.')[1];
var patch = version.split('.')[2];
var minor_updated = Number(minor) +1;
var version_updated = major + '.' + minor_updated + '.' + patch;
console.log("Nova versao: " + version_updated);
obj.version = version_updated;
let data = JSON.stringify(obj, null, 2);
fs.writeFileSync('package.json', data);
package.json
{
"name": "testeapp",
"version": "0.14.0",
"scripts": {
"ng": "ng",
"prestart": "ts-appversion",
"start": "ng serve",
"prebuild": "ts-appversion",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"bd": "node ./appversionupdate.mjs && npm run build && firebase deploy"
},