如何从JSON对象获取数据到Angular?

时间:2019-05-02 13:49:14

标签: json angular key

对于数组列表的情况(带有括号),一切正常

这对我来说正常工作:

export interface IPage {
  size: number;
pageSize: number;
numberOfPage: number;
object: ICompany[];
}

export interface ICompany {
name: string;
country: string;
taxID: string;
numberOfAds: number;
}

[{
  "size": 10,
  "pageSize": 20,
  "numberOfPage": 1,
  "object": [
    {
      "name": "Pirates Limited",
      "country": "Poland",
      "taxID": "e",
      "numberOfAds": 1
    },
    {
      "name": "Test company",
      "country": "Poland",
      "taxID": "fads",
      "numberOfAds": 2
    }
}]

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { IPage} from './page';
import { Observable } from 'rxjs';

@Injectable()
export class CompanyService {

//private _url: string = "http://localhost:4200/api/company?page=1";
private _url: string = "/assets/data/page.json";


  constructor(private http:HttpClient) { }

getCompany(): Observable<IPage>{
    return this.http.get<IPage>(this._url);
  }
  errorHandler(error: HttpErrorResponse){
    return Observable.throw(error.message || "Server Error");
}


}

index.componenet.ts 
this._companyService.getCompany()
.subscribe(data => this.company = data,
                 error => this.errorMsg = error);

index.componenet.html

 <ul *ngFor="let c of company">
      <li>{{c.size}}, {{c.pageSize}}</li>
    </ul>

但是当我更改为json对象(不带[])时:

{
  "size": 10,
  "pageSize": 20,
  "numberOfPage": 1,
  "object": [
    {
      "name": "Pirates Limited",
      "country": "Poland",
      "taxID": "e",
      "numberOfAds": 1
    },
    {
      "name": "Test company",
      "country": "Poland",
      "taxID": "fads",
      "numberOfAds": 2
    }
}

这对我不利。不使用JSON数组时需要做什么?如果我不使用列表,该怎么做。此键值代码对我不起作用。

2 个答案:

答案 0 :(得分:0)

您可以添加逻辑以检查结果是否为数组,如果没有将其转换为数组。

this._companyService.getCompany()
.subscribe(data => {
    if(!Array.isArray(obj)){
    this.company = [data]
    }else{
     this.company = data;
    }
},
error => this.errorMsg = error);

答案 1 :(得分:0)

通过RxJS运算符映射结果:

return this.http.get<IPage>(this._url).pipe(map(a => a[0]));

这将返回数组的第一个元素。

相关问题