简体   繁体   English

从 url 调用 json 文件

[英]Call json file from url

I'm trying to call json file from url and get data.我正在尝试从 url 调用 json 文件并获取数据。 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);
    });
  }

You make the GET request on the service, where you convert the request into a promise with toPromise() .您在服务上发出GET请求,并使用toPromise()将请求转换为 promise。 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 ()从那里在任何组件中,您可以调用构造函数this.serviceJson()中声明的服务的方法,并使用 .then .then ().catch ()解析 promise

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);
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM