0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

What if I want to display the "WrapperType" for example?
Also the JSON.stringify just shows the json response, I want to log all the data as it comes back in JSON format
just access using dot operator
like results.wrapperType

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.