簡體   English   中英

在 Angular 中顯示來自 api 的數據時出現問題 6

[英]Problem with displaying data from api in Angular 6

在我的應用程序中,我調用了 iTunes api,當我記錄響應時,它會返回 [object object]。 我知道這一定與api的數組結構有關。 我有一個服務被注入到一個組件中,如下所示:順便說一句,我有一個用於 api 的 proxy.conf.json 文件。

服務.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class ApiService {

  api: string = 'api';

  constructor(
    private http: HttpClient,
  ) { }

  getAll(): Observable<any> {
    return this.http.get<any>(this.api)
      .pipe(
        catchError(this.handleError)
      );
  }
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };
}

組件.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { ApiService } from '../../../services/api.service';


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

  public results = [];

  constructor(private service: ApiService) { }
  private http: HttpClient
  ngOnInit() {
    this.getApi();
  }

  private getApi() {
    this.service.getAll().subscribe((results) => {
      console.log('JSON Response = ' + results);
    })
  }
}

Api結構

{ 
   "resultCount":50,
   "results":[ 
      { 
         "wrapperType":"track",
         "kind":"song",
         "artistId":271256
      },
   ]
}

有任何想法嗎?

格式正確,如果要查看為 JSON,則需要使用 JSON.stringify

 this.service.getAll().subscribe((results) => {
      console.log('JSON Response = ' + JSON.stringify(results));
      data = results.results;
})

如果你想用 ngFor 迭代元素

 <li *ngFor="let dataObj of data">
      {{ dataObj.wrapperType}}
 </li>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM