angulartypescript

Angular Http Client Call is not returning value to component but shows response in browser's network tab


I have a component that renders a map view. The data for the map is fetched from backend service call. I tried to live debug on the browser's dev tools. It gets to the service call and seems to skip the service call. But when I checkout the network traffic the service call returned values and was successful. I think the component is loading before the service call is completed.

this is what the init component looks like

ngOnInit(): void {
    this.myService.getData().subscribe(
        (result) => {
            this.data = result.body;
        }, 
        (result: HttpErrorResponse) = {
            console.log(result.error);
        }
    );
    this.loadMap();
}

During execution, it gets past the service call and loads the map. 'this.data' appears empty. I tried adding a condition around this.loadMap() to make sure there is data but that just stops the render. The component doesn't seem to wait for the service call to complete. I tried using *ngIf to check for results before component loads and that didn't help. How can I load this.data before the component renders?


Solution

  • If I understand correctly, you have to wait for the response of the API call /getData()/ and only then call rendering /this.loadMap()/.

    You should set the this.data variable in a tap operator, and call the load method in the subscribe.

    this.myService.getData().pipe(tap((result)=> {
        if(result instanceof HttpErrorResponse)  {
          console.log(result.error);
        }
        this.data = result.body;
    })).subscribe(()=> {
      this.loadMap();
    });