Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to constantly ask clients to refresh the page manually after each modification. Despite my attempts to retrieve the main.[hash].js file from the dist folder and compare it with new versions, I have not been successful. Likewise, experimenting with serviceWorker did not yield the desired results. Even after extensively searching on StackOverflow, I have yet to find a satisfactory answer to automate page refreshing when deploying a new version to my Angular 7 project hosted on Firebase. Thank you for any assistance.

Here is my latest attempt using serviceWorker:

log-update.service.ts

isUpdateAvailable = new Promise((resolve, reject) => {
    console.log('calling isUpdateAvailable');
    if ('serviceWorker' in navigator && ['localhost', '127'].indexOf(location.hostname) === -1) {
      // register service worker file
      navigator.serviceWorker.register('service-worker.js')
        .then(reg => {
          reg.onupdatefound = () => {
            const installingWorker = reg.installing;
            installingWorker.onstatechange = () => {
              switch (installingWorker.state) {
                case 'installed':
                  if (navigator.serviceWorker.controller) {
                    // new update available
                    console.log('New update available...');
                    resolve(true);
                  } else {
                    // no update available
                    resolve(false);
                  }
                  break;
              }
            };
          };
        })
        .catch(err => console.error('[ERROR]', err));
    }
    console.log('Dev mode...');
  });

app.component.ts

ngOnInit() {
    this.logUpdateService.isUpdateAvailable.then(isAvailable => {
      if (isAvailable) {
        alert('New update found !');
      } else {
        console.log('No new update found.');
      }
    });
}

Answer №1

I incorporated Workbox into my PWA and it functions flawlessly. By utilizing workbox-window, it is possible to easily identify a new service worker installation and prompt the user to either restart the application or automatically restart it without needing authorization. For more in-depth information, I recommend checking out this article.

Answer №2

After receiving insights from @Mises and @Vash72, I devised a service named log-update.service.ts which houses three functions:

isAvailable()

newVersion()

sameVersion()

I then implemented a button on my dashboard to toggle the state of the isAvailable field in Firestore database to TRUE. Subsequently, I called the isAvailable function in main.ts within the ngOnInit() method. Whenever the isAvailable field in Firestore changed to TRUE, I refreshed the page for the client and reverted the field back to FALSE.

log-update.service.ts:

export class LogUpdateService {
  updateCollection: AngularFirestoreCollection<Update>;

  constructor(private afs: AngularFirestore) {

  }

  isAvailable() {
    return this.afs.collection('update').doc('available');
  }

  newVersion() {
    const newversion: AngularFirestoreDocument<any> = this.afs.doc(`update/available`);
    newversion.update({isAvailable: true}).then(res => {
      console.log('Set new version to true');
    }).catch(err => {
      console.log(err);
    });
  }

  sameVersion() {
    const newversion: AngularFirestoreDocument<any> = this.afs.doc(`update/available`);
    newversion.update({isAvailable: false}).then(res => {
      location.reload();
    });
  }

}

update.ts:

export interface Update {
  isAvailable: boolean;
}

main.ts:

this.logUpdateService.isAvailable().valueChanges().forEach(res => {
      // @ts-ignore
      if (res.isAvailable) {
        console.log('refresh');
        this.logUpdateService.sameVersion();
      } else {
        console.log('No update.');
      }
    });

EDIT: However, there are some challenges. If someone closes the website and revisits later, they will see the same content due to caching. Additionally, if the website tab is not active, no action will be taken as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Sorting through an array of objects using a filter method

While following a tutorial, I decided to make some changes to the TypeScript for learning purposes. However, I encountered a problem when trying to create a filter function from a React context script. I have successfully implemented a function called get ...

Executing a function when the date changes in ng2-datepicker

Currently, I am incorporating ng2-datepicker into my project and the corresponding HTML code appears as follows: <datepicker [(ngModel)]="selectedDate"></datepicker> I am uncertain about how to trigger a function when the date is modified ...

NG8003 error: ExportAs 'ngForm' directive not found in the system

I encountered an issue with my first Angular 11 project: No directive found with exportAs 'ngForm'. Despite importing FormsModule and ReactiveFormsModule in app.module.ts, the error persists. Here is the code snippet: This is from product.compon ...

What could be the reason for the route animation failing to work in Angular2?

App.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from "@angular/http"; import { BrowserAnimat ...

The ng-repeat functionality in Angular 2 is not functioning correctly when trying to select an option from an array of objects. Instead of displaying the actual object, it is

When using ngRepeat in Angular 2, I have found that selecting options from an array of strings works perfectly fine. However, when the data is an array of objects, the ngModel displays '[Object object]' instead of the selected object. I have trie ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

Firestore fails to store the complete object when using addDoc

Greetings! I've encountered an issue with firebase when attempting to addDoc passing an object using the useState Hook. The problem arises where sometimes the object is stored with all fields, and other times only some are stored (despite passing the ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Is it possible to enforce a certain set of parameters without including mandatory alias names?

My inquiry pertains to handling required parameters when an alias is satisfied, which may seem complex initially. To illustrate this concept, let's consider a practical scenario. If we refer to the Bing Maps API - REST documentation for "Common Param ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

Type definitions in Typescript for the style property of Animated.View

One of my components has a Props interface that extends ViewProps from React Native, like this: export interface Props extends ViewProps { // Custom props } As a result, this also extends the style prop. However, I am facing an issue while using Animat ...

Guide to navigating to a specific route based on location in a Node.js Express application

Currently, I am integrating the official i18n library to localize my Angular Universal application and utilizing a proxy to deliver the localized versions. The app is functioning properly when there is a language specified in the URL (e.g: /en/page), but e ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Exploring the world of TypeScript type mappings

I'm currently working on enhancing a function with type annotations. This particular function takes an array of typed objects as parameters and returns a mapped array of a different type: const createAnimals = <T extends AnimalFactory<any>[]& ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...

What is the process for updating information once the user has verified their email address on Supabase using Next.js

After a user signs up using a magic link, I want to update the profiles table in my database. Below is the code snippet I am currently using: Login.tsx import { useState } from "react"; import { supabase } from "../lib/initSupabase"; c ...