1

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 []):

{
  "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? What change should I make if I do not use the list. This code for the key value does not work for me.

1
  • you cannot loop on a object. you can only loop on an array. convert it into an array. Commented May 2, 2019 at 14:01

2 Answers 2

1

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

Comments

0

Map the result woth RxJS operators :

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

This will return the first element of the array.

Comments

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.