简体   繁体   English

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

[英]How to get data from JSON object to Angular?

For the array list case (with bracket) everything works fine 对于数组列表的情况(带括号),一切正常

This work properly for me: 这对我来说正常工作:

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>

but when i change to json object (without []): 但是当我更改为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
    }
}

It does not work good for me. 它对我不利。 What i need to do when I do not use JSON array? 不使用JSON数组时需要做什么? What change should I make if I do not use the list. 如果我不使用列表,该怎么做。 This code for the key value does not work for me. 此键值代码对我不起作用。

You can add logic to check result is array or not, if not convert it to array. 您可以添加逻辑以检查结果是否为数组,如果没有将其转换为数组。

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

Map the result woth RxJS operators : 将结果映射到RxJS运算符:

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

This will return the first element of the array. 这将返回数组的第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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