【问题标题】:Angular unable to display API results in htmlAngular 无法在 html 中显示 API 结果
【发布时间】:2021-01-25 22:52:50
【问题描述】:

在 Angular 中,为什么我无法显示 API 调用的结果?

从 API 调用返回的 JSON。我要显示value属性。

{
  "data": [
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APALE"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "9695006WHN4DWDKBF403"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/9695006WHN4DWDKBF403"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APPLITEC"
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "AppLogic"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "724500S2JQ8M9Q67N911"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/724500S2JQ8M9Q67N911"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APPRECIO"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "969500ZFBM0TC2T1HV85"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/969500ZFBM0TC2T1HV85"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "AMPLEGEST"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "969500DYMLRK8URCGP47"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/969500DYMLRK8URCGP47"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "ANPLEX OÜ"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "254900RNJSFWJXOZE551"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/254900RNJSFWJXOZE551"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "Apleks OÜ"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "254900VZB706EXH22533"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/254900VZB706EXH22533"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APPLE-WAY"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "969500QV2N8IIVULLH93"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/969500QV2N8IIVULLH93"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APPLICOMM"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "969500MCJ58VYVTX3715"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/969500MCJ58VYVTX3715"
          }
        }
      }
    },
    {
      "type": "fuzzycompletions",
      "attributes": {
        "value": "APPLIQ AS"
      },
      "relationships": {
        "lei-records": {
          "data": {
            "type": "lei-records",
            "id": "8945006S1SZMS8HKLR20"
          },
          "links": {
            "related": "https://api.gleif.org/api/v1/lei-records/8945006S1SZMS8HKLR20"
          }
        }
      }
    }
  ]
}

我有一个用于连接 API 的 service.ts 文件

import { HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class GleifService {

  private gleifUrl = 'https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q=';  // URL to web api
  private data:any = []

  constructor(private http: HttpClient) {}

  getGleif(name: string){
    const url = `${this.gleifUrl}${name}`;
    this.http.get(url).subscribe((res)=>{
      this.data = res
      console.log(this.data)
    })
  }

}

一个component.ts文件

import { Component, OnInit } from '@angular/core';

import { GleifService } from '../gleif.service';

@Component({
  selector: 'app-security',
  templateUrl: './security.component.html',
  styleUrls: ['./security.component.css']
})
export class SecurityComponent implements OnInit {

  // array for storing the data
  private data:any = []

  constructor(private gleifService: GleifService) { }

  getGleif(name: string): void {
    this.data = this.gleifService.getGleif(name);
  }

  ngOnInit() {
    this.getGleif(name);
  }

}

还有一个用于显示结果的 .html 文件


<div>
  <label>Company ID:
    <input placeholder="Autofill"/>
  </label>
</div>

<div>
  <label>Company Name:
    <input #Name placeholder="A Company Ltd"/>
    <button (click)="getGleif(Name.value); Name.value=''">Search</button>
  </label>
</div>

<div *ngFor="let entry of data?.data" style="text-align:center">
  <h3>
     header works: {{ entry.type }}
   </h3>
</div>

我可以在控制台响应中看到结果。如何访问和显示 API 调用的结果?

【问题讨论】:

  • 也许是因为getGleif(name: string) 中的GleifService 没有return 什么?该函数仅设置一个局部变量。阅读内容:angular.io/guide/http

标签: html json angular api


【解决方案1】:

这是因为您从服务订阅了 http 调用,而不是返回它的数据。一旦您在服务中订阅了调用,除非您从 http 返回可观察值并让组件订阅它的响应或数据,否则不会返回任何数据

将您的代码改为:

服务

import { Observable } from 'rxjs';

...

getGleif(name: string): Observable<any> {
  const url = `${this.gleifUrl}${name}`;
    
  return this.http.get(url);
}

组件

...

getGleif(name: string): void {
  this.gleifService
    .getGleif(name)
    .subscribe(res => this.data = res); 
}

或者在你的组件中你也可以这样做:

...

data$: Observable<any>;

getGleif(name: string): void {
  this.data$ = this.gleifService.getGleif(name);    // we have assigned it with an Observable variable since the return of this service is of Observable type that needed to be subscribe into
}

模板

...

// Since the data$ is async, we use pipe async to fetch it's raw data
<div *ngFor="let entry of (data$ | async)?.data" style="text-align:center">
...
</div>

【讨论】:

    【解决方案2】:

    也许你需要订阅component.ts文件中的结果

    getGleif(name: string): void {
        this.gleifService.getGleif(name).subscribe((result) => {
            this.data = result
        });
    }
    

    【讨论】:

      【解决方案3】:

      确保从服务返回数据并在组件文件中订阅。 并且您不需要在 ngOnInit 中调用该函数,因为您将在单击搜索按钮时调用它。

      componet.ts 文件

      import { Component } from "@angular/core";
      import { GleifService } from "./service";
      
      @Component({
        selector: "app-root",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"]
      })
      export class AppComponent {
        // array for storing the data
        private data: any = [];
      
        constructor(private gleifService: GleifService) {}
      
        getGleif(name: string): void {
          this.gleifService.getGleif(name).subscribe((response: any) => {
            this.data = response.data;
          });
        }
      }
      

      component.html 文件

      <div>
        <label
          >Company ID:
          <input placeholder="Autofill" />
        </label>
      </div>
      
      <div>
        <label
          >Company Name:
          <input #Name placeholder="A Company Ltd" />
          <button (click)="getGleif(Name.value); Name.value=''">Search</button>
        </label>
      </div>
      
      <div *ngFor="let entry of data" style="text-align: center;">
        <h3>
          header works: {{ entry.type }}
        </h3>
      </div>
      

      service.ts 文件

      import { HttpClient } from "@angular/common/http";
      import { Injectable } from "@angular/core";
      
      @Injectable({
        providedIn: "root"
      })
      export class GleifService {
        private gleifUrl =
          "https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q="; // URL to web api
      
        constructor(private http: HttpClient) {}
      
        getGleif(name: string) {
          const url = `${this.gleifUrl}${name}`;
          return this.http.get(url);
        }
      }
      

      工作codesandbox

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 2015-11-16
        • 2017-07-27
        • 1970-01-01
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多