Reputation: 25
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.
Upvotes: 1
Views: 501
Reputation:
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.
Upvotes: 0
Reputation: 18975
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);
Upvotes: 1