Search code examples
angulartypescriptangular-httpclient

How to sync data between same web page on different browsers using Angular 8


I have created an angular application where I am receiving data using Angular HttpClient which is consuming REST API , the data received is the values which I have to display in the the page which is just a form. If I edit the data and click on save, the data gets saved through HttpClient and is a put call to REST API.

Since I am new to angular, so my problem is if I open the same page in two different browsers and I make change in one of the browser, I want the changed data to get reflected in other browser as well. How to make this possible using Angular 8?

Call to rest api is written in seperate service as follows:

getData(): Observable<IData> {
   return this.http.get(`${this.serverurl}`);
}

updateData(data: IData): Observable<IData> {
   return this.http.put<IData>(`${this.serverurl}/save`, data);
}

Call to service is done as:

ngOnInit() {
  this.myHttpService.getData().subscribe(
    data => {
      this.myData = Object.assign({}, data);
    }
  );
}

onSaveClick() {
  if (this.myData) {
    this.myHttpService.updateData(this.myData).subscribe(
      response => {
        this.myData = response;
      }
    );
  }
}

What extra thing do I need to do?


Solution

  • I figured out the solution by using Interval(https://rxjs-dev.firebaseapp.com/api/index/function/interval) and putting my get call under interval:

    ngOnInit() {
      interval(1000).pipe(
      takeWhile(() => this.alive)).subscribe(() => {
        this.myHttpService.getData().subscribe(
          data => {
            this.myData = Object.assign({}, data);
          }
        );
       });
      }