Home > database >  Angular - Getting JSON data from HttpClient in a service not working properly
Angular - Getting JSON data from HttpClient in a service not working properly

Time:06-24

I'm trying to get JSON data in Angular using a service and I'm getting data with HttpClient using the get() method. The problem is I'm using Promise and the function is returning a promise with the value inside it.

I printed the value in the console and it's returning:

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)} controls: (22) [{…}, {…}, {…}, {…}, {…}, {…}, {…},}

enter image description here

Here is the service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable,of, interval, firstValueFrom } from 'rxjs';
import { Component, OnInit,Input } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder, Validators  } from '@angular/forms'
import {STEPPER_GLOBAL_OPTIONS} from '@angular/cdk/stepper';
import { map } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class DataService {

  controls:any=[]

  constructor(private http: HttpClient) {
    this.controls=this.getControlsData()
  }

  public async getControlsData():Promise<any> {

    console.log(firstValueFrom( (this.http.get("../assets/json/controlsData.json"))))
    return await firstValueFrom( (this.http.get("../assets/json/controlsData.json")))
  }

  public addControl(): Observable<any> {
    return this.http.get("../assets/json/controlsData.json");
  }



}

Component:

ngOnInit() {

    this.data=this.DataService.getControlsData()

}

CodePudding user response:

Either make the ngOnInit() method asynchronous.

async ngOnInit() {
   this.data = await this.DataService.getControlsData();
}

Or assign the value during callback via Promise.then().

ngOnInit() {
  this.DataService.getControlsData().then((response: any[]) => {
    this.data = response;
  });
}

Or would suggest not to use Promise but return an observable, so your component to subscribe the observable (depend on your use case if you able to select not to stick with Promise).

  • Related