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

Is it possible to verify email input without including standard domains?

Looking to implement validation that excludes common email domains like gmail.com or outlook.com in my project. Here is the current code I have, how can this type of validation be implemented? onboarding.component.html <div class="w-full my-3 md:i ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

What is the TypeScript term for assigning multiple parameters an alias?

Imagine having a piece of code structured like this: export async function execute(conf: Record<string, string>, path: string, params: Array<string>) { const cmd = params[1]; const commandOption = params.slice(2) switch(cmd){ ...

Can you explain the significance of ?. in Angular 5?

While I understand that product.id == 1 ? stuff : not stuff simplifies to choosing "stuff" if the id is 1 and "not stuff" otherwise, I am unsure about the meaning of the following code: product?.id.name ...

Unique TypeScript code snippets tailored for VSCode

Is it possible to create detailed custom user snippets in VS Code for TypeScript functions such as: someArray.forEach((val: getTypeFromArrayOnTheFly){ } I was able to create a simple snippet, but I am unsure how to make it appear after typing an array na ...

Setting up Angular on your Mac

Recently, I attempted to set up Angular on my macOS system. After confirming that I have npm 5.6.0 and node 8.11.1 installed, I proceeded with sudo npm install -g @angular/cli. It appeared to be successful at first, but upon running ng --version, the follo ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

User is automatically logged in upon account completion

Is there a way to improve user experience in my app by implementing Firebase authentication so that: Users do not need to log in again after creating an account Users are automatically logged in after creating an account To achieve this, I am follow ...

Can you provide instructions on how to use RXJS Observables to conduct a service poll?

If I want the get request to "api/foobar" to repeat every 500 milliseconds, how can I modify the code provided below? import {Observable} from "RxJS/Rx"; import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; @Injectable() export ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Formula for a distinct conclusion of written words

Can I restrict input to only letters and numbers, with words like xls, xlsx, json, xml always appearing at the end of the line? This is the pattern I am currently using: Validators.pattern(/^[a-zA-Z0-9]+$/) ...

Unable to Anticipate User Input in Angular Using Scanner or Keyboard

Currently grappling with Angular 6 and facing an issue. I have a text box and a submit button, with a requirement for functionality to allow input through either manual keyboard typing or a Barcode scanner. The desired behavior is for the submit button to ...

Unable to set up ng-bootstap on Angular version 16.1.3

Upon attempting to integrate ng-bootstrap with Angular 16.1.3, an error was encountered during installation: Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...

Activate the onclick event for HTML select-options when there is only a single option available

My HTML select dropdown features 5 options, which are a list of car manufacturers. When a user clicks on an option, the onchangeHandler triggers to capture the selected value. Based on this selection, another dropdown displaying car models is shown to the ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

Guide to incorporating dynamic components into Angular Router

I am currently working on developing a pluggable Angular application. During my research, I came across the following insightful article: Building an extensible Dynamic Pluggable Enterprise Application with Angular Everything was going smoothly until I ...

Express: issue retrieving numbers from request body array

JavaScript / TypeScript Issue: export const updateSettings = catchErrors(async (req, res) => { console.log("updateSettings req.body: ", req.body) const { organizationId, formdata, updatedItems, updateQuota } = req.body; console.lo ...