2

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
  • Can you reproduce it on Stackblitz? Anyway, the website where you're trying to get the json has an expired certificate and presents a 404, I expect it to return an error, but it can be related Commented Jun 2, 2021 at 23:51

1 Answer 1

1

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);
    });
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please explain?
Ok, make shore you use async/await.
Thanks for your answer.., I got error url A class member cannot have the 'const' keyword

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.