Search code examples
angulardatabasetypescriptfirebasereload

Angular and Firebase - Automatic database recovery


I try to create a website offering text courses for my school assignment. I have already done the authentification and the courses backup. Now, I try to create a live chat. But, when I change the database, it is necessary to reload the website to have the change. How to do it without reload?

My service to load script:

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable()
export class CoursService {
  liste_cours = []

  constructor(private httpClient: HttpClient) {
    this.getCoursFromServer()
  }

  saveCoursToServer() {
    this.httpClient
      .put("https://databaselink/cours.json", this.liste_cours)
      .subscribe(
        () => {
          console.log("Enregistrement terminé!");
        },
        error => {
          console.log("Erreiorr ! : " + error);
        }
      );
  }

  getCoursFromServer() {
    this.httpClient
      .get<any[]>("https://databaselink/cours.json")
      .subscribe(
        response => {
          this.liste_cours = response;
          console.log("Loading finish");
        },
        error => {
          console.log("Error!: " + error);
        }
      );
  }
}

Thanks for your answers!


Solution

  • It looks like you're accessing the Firebase Realtime Database by making HTTP requests to it. This means that you get the current data when you make the HTTP call, but don't receive updates to the data after that. When you reload the page, you one again get the latest data.

    There are a few ways to make your page auto-update when the data changes, without requiring the user to reload the page.

    1. Use the Firebase SDK. This is by far the easiest approach, as Firebase has SDKs for both plain JavaScript, and for Angular apps. When you integrate these SDKs, you can get realtime updates by attaching an on('value' listener, or by subscribing to the node.
    2. Perform the HTTP request periodically in your page, which is known as polling the data. This is a quite simple approach too, but becomes very inefficient if your data doesn't change frequently.
    3. Implement a client for Firebase's streaming REST API. This is quite complex and typically only done on platforms where there is no Firebase SDK, or by enthusiast who want to learn more about the protocol.

    I highly recommend you consider these solutions in the order they're given.