【问题标题】:Problem with displaying data from api in Angular 6在 Angular 6 中显示来自 api 的数据的问题
【发布时间】:2020-03-12 05:18:16
【问题描述】:

在我的应用程序中,我正在调用 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
      },
   ]
}

有什么想法吗?

【问题讨论】:

    标签: javascript json angular typescript api


    【解决方案1】:

    格式正确,如果想看成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>
    

    【讨论】:

    • 例如,如果我想显示“WrapperType”怎么办?
    • 另外 JSON.stringify 只显示 json 响应,我想记录所有以 JSON 格式返回的数据
    • 只使用点运算符访问
    • 喜欢 results.wrapperType
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2020-11-04
    • 2021-07-25
    相关资源
    最近更新 更多