Call json file from url

Viewed 113

I'm trying to call json file from url and get data. But no error and nothing working. I don't have any idea how to solve it.

service

export class JsonService {


  public getMenuData(): Observable<any> {
    
    return new Observable((observer) => {
      this.http.get('https://demored.ddns.net:50443/demored/path_image/menu.json').subscribe((response)=> {
        observer.next(response);
        observer.complete();
      });
    });
  }

Component

ngOnInit() {

    this.getJson();
    
  }

  getJson(){
    this.jsonService.getMenuData().toPromise().then(data => {
      this.menuJson = data;
      console.log("Menu from json file ",this.menuJson);
    }).catch((err) => {
      console.log('error in fetching data',err);
    });
  }
1 Answers

You make the GET request on the service, where you convert the request into a promise with toPromise(). From there in any component you can call the method for the service declared in the constructor this.serviceJson() and resolve the promise with a .then () or .catch ()

export class JsonService {
  
  getMenuData(): Promise<any> {
   return this.http.get<any>('https://demored.ddns.net:50443/demored/path_image/menu.json').toPromise()
  }

component

  ngOnInit() {

    this.getJson();
    
  }

  async getJson(){
   await this.jsonService.getMenuData().then(data => {
      this.menuJson = data;
      console.log("Menu from json file ",this.menuJson);
    }).catch((err) => {
      console.log('error in fetching data',err);
    });
  }
Related