简体   繁体   中英

Problem with displaying data from api in Angular 6

In my app I am calling the iTunes api and when I log the response it is coming back with [object object]. I know it must be to do with the array structure of the api. I have a service being injected into a component as follows: BTW I have a proxy.conf.json file for the api.

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 structure

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

Any ideas?

The format is correct, if you want to see it as a JSON, you need to use JSON.stringify

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

if you want to iterate over elements with ngFor use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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