Angular не может отображать результаты API в html

#html #json #angular #api

#HTML #json #angular #API

Вопрос:

Почему в Angular я не могу отобразить результаты вызова API?

JSON, возвращенный из вызова API. Я хочу отобразить атрибут 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"
          }
        }
      }
    }
  ]
}
  

У меня есть файл service.ts для подключения к API

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

@Injectable({
  providedIn: 'root'
})

export class GleifService {

  private gleifUrl = 'https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalNameamp;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?

Комментарии:

1. Может быть, это потому getGleif(name: string) , что in GleifService ничего не return делает? Эта функция устанавливает только локальную переменную. Что-то для чтения: angular.io/guide/http

Ответ №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:

не забудьте вернуть данные из сервиса и подписаться внутри файла компонента. и вам не нужно вызывать функцию внутри 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.legalNameamp;q="; // URL to web api

  constructor(private http: HttpClient) {}

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

рабочий codesandbox

Ответ №3:

Возможно, вам нужно подписаться на результат в component.ts файле

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