0

I am trying to load a json data from backend service to my angular app. I want to load/push data into an array. Below is what my data from backend looks like

{   "Record":[
  {
     "Name":"John",
     "Place":"Seattle"
  },
  {
     "Name":"AS2",
     "Place":"DC"
  }]}

Here is my array model class in typescript

export class EventMaster {
  public name: string;
  public cityName: string;
  constructor (name: string, cityName: string){
    this.cityName = cityName;
    this.name = name;
  }
}

Here is my typescript code which I am using to fetch data from back-end and load into array

  private eventMaster: EventMaster[] = [
   new EventMaster('Loan', 'Approved' )
  ];

  onFetchData(form: HTMLFormElement){
    console.log(form);
    console.log(form.value);
    this.nameCity = new NameCity(form.value.name, form.value.city);

    this.fetchDataService.fetchData(this.nameCity).subscribe(
      (data: EventMaster[]) => {
        console.log(data);
        this.eventMaster.push(...data);
        console.log(this.eventMaster.length);
      }
        );

  }

Here is my http get call

 fetchData(nameCity: NameCity) {

  return this.http.get<EventMaster[]>(this.baseURL);

  }

When I try to check the length of array it always shows as 1 and not 2. What am I doing wrong?

1
  • try this this.eventMaster = [...this.eventMaster, ...data]; instead of push. Commented Mar 9, 2018 at 12:59

2 Answers 2

1

You need to map the result of your get API call

fetchData(nameCity: NameCity) {
    return this.http.get(this.baseURL).map((res: any) => res.Record.map(r=>new EventMaster(r.Name, r.Place));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Based on my understanding , if I am using HTTPClient then angular does extract the body for me. So I need not to use "map". Is that incorrect ?
You don't need to use map if the structure of your json data corresponds to the structure of the models declared in angular. In your example, actualy data is wrapped in a Record property, and has Name and Place properties instead of name and cityName in your model. You can just do a console.log(data) in your question's code to check that it's going to be empty
0

How is onFetchData executed? It might be running only once. Also place console.log(this.eventMaster.length); outside of this function and try

1 Comment

The backend call was completed and I could see the response in console when I log data. It's just not getting loaded into array

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.