在Angular 6中显示来自api的数据的问题

时间:2019-11-16 04:00:07

标签: javascript json angular typescript api

在我的应用中,我正在调用iTunes api,当我记录响应时,响应将与[object object]一起返回。我知道这一定与api的数组结构有关。我将服务注入到组件中,如下所示:顺便说一句,我有用于api的proxy.conf.json文件。

service.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!'));
  };
}

component.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
      },
   ]
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

格式正确,如果要以JSON格式查看,则需要使用JSON.stringify

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

如果要使用ngFor use遍历元素

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