Reputation: 113
I am newbie to typescript and angular 2. I am finding it hard to access an array object value from a http response. Below is the code.
Below is the rdcModel defition
class RdcModel {
constructor(
public rdcList: Array<RdcList>
) { }
}
class RdcList {
constructor(
public rdcNumber: number,
public rdcName: string,
) {}
}
export { RdcModel, RdcList };
using the below Api service to retrive the data and returning the rdcModel.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { RdcModel } from './model/rdc.model';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient) {}
getRdc$(): Observable<RdcModel[]> {
return this.http
.get('https://web.server.com/RDCUI/rs/rdc')
.catch(this._handleError);
}
private _handleError(err: HttpErrorResponse | any) {
const errorMsg = err.message || 'Error: Unable to complete request.';
return Observable.throw(errorMsg);
}
}
Below is the response that I get when I call the api.
{
"rdcList":[
{
"rdcNumber":8756,
"rdcName":"DALLAS"
},
{
"rdcNumber":4251,
"rdcName":"TOPEKA"
}
]
}
In the component, I am trying to access the rdclist[1]
rdcModel: RdcModel[] = [];
this.dcSub = this.api
.getRdc$().subscribe(
res => {
this.rdcModel = res;
console.log(this.rdcModel[0]);
},
err => {console.error(err); }
);
It gives me undefined when I try to acess [0]. How should I access the values of each RDC and store it an array? Any help is much appreciated.
Upvotes: 0
Views: 3227
Reputation: 55
let's say you have created a model of how your data will look like.. My Model is called ModelClass
export interface ModelClass{
name: string;
age: number;
}
Then create your array with the object type of ModelClass
student: ModelClass[] = [];
And how to get value in that array--> Assume this code is in for loop or forEach loop... or whatever looping style u r comfortable
student[i].name;
student[i].age;
i ---> is index of the loop... Try convert this in ur HTTP code..
Upvotes: 0
Reputation: 2736
check the below code. I am not sure whether your response is array of objects or not. if it's array of objects just iterate the rdcModel and put console to check
rdcModel: any;
this.dcSub = this.api
.getRdc$().subscribe(
res => {
this.rdcModel = res;
console.log(this.rdcModel.rdcList[0]);
},
err => {console.error(err); }
);
Upvotes: 1