Search code examples
angularrxjsangular-httpclient

Parse Angular Http Reponse And Handle Json


I have a code that calls http post and recieves the observable notification when data is recieved . I wish to know how to get the json respose from the server in the following function since when I try to print it it only shows the observable and not the actual json returned from the server:

 display = response => {
      console.log(response);
  };

The complete code is :

import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of, Subject } from 'rxjs';
import { delay, tap, mergeMap, repeat, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  private ngUnsubscribe = new Subject<void>(); // Subject for unsubscribing

  constructor(private http: HttpClient) { }

  callOmni = () => of(this.pollOmni()).pipe();

  display = response => {
      console.log(response);
  };

  poll = of({}).pipe(
    mergeMap(_ => this.callOmni()),
    tap(this.display),
    delay(10),
    repeat(),
    takeUntil(this.ngUnsubscribe) // Unsubscribe when ngUnsubscribe emits
  );

  pollOmni() {
    return this.http.post<any>('http://127.0.0.1:8044/api', { call: 'getInfo' });
  }

  ngOnInit() {
    this.poll.subscribe();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next(); // Emit value to unsubscribe from ongoing subscriptions
    this.ngUnsubscribe.complete(); // Complete the subject
  }
}

Solution

  • The error is in callOmni = () => of(this.pollOmni()).
    this.poolOmni already returns an observable, which you are wrapping in another observable with of.
    If you call directly poolOmni the code should work fine