Get and store JSON data via HttpClient in Angular 6

In Angular 6, I want to get JSON data (an array of objects) from http://jsonplaceholder.typicode.com/todos and store them to a tempArray. I have done in an arrow function, but after arrow function, tempArray is undefined.

For example, when I want to print the first element of tempArray via console.log(), the result is undefined. How should I do this?

My code is:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface DataResponse {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor( private http: HttpClient ) {}

  ngOnInit(): void { 

    var tempArray: DataResponse[] = [];
    this.http.get('http://jsonplaceholder.typicode.com/todos').subscribe(data => {
      for (var i=0; i<10; i++)  
        tempArray.push(<DataResponse>data[i]);     
    });
    console.log( tempArray[0] );
  }
}

2 answers

  • answered 2018-08-16 08:41 Muhammed Ozdogan

    javascript is asycnc. After you request to the server you are intermediately writing your array first element to console so even response is not recived to you.

    So try this:

      var tempArray: DataResponse[] = [];
        this.http.get('http://jsonplaceholder.typicode.com/todos').subscribe((data: DataResponse[]) => {
          /// tempArray = data.slice(); If you want to clone recived data.
        tempArray = data
        console.log( tempArray[0] );
        });
    

    Check this out: How do I return the response from an asynchronous call?

  • answered 2018-08-16 10:47 Iman

    I finally found the solution. The subscribe function has 3 parameters, second and third are optional. The second parameter is when an error occurs and the third parameter is when the all of data is received and at this time we can print the tempArray:

    import { Component } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    interface DataResponse {
      userId: number;
      id: number;
      title: string;
      completed: boolean;
    }
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      constructor( private http: HttpClient ) {}
    
      ngOnInit(): void { 
    
        var tempArray: DataResponse[] = [];
        this.http.get('http://jsonplaceholder.typicode.com/todos').subscribe(
          data => {
                    for (var i=0; i<10; i++)  
                      tempArray.push(<DataResponse>data[i]);     
                  },
          error=> { 
                    console.log("Error in recieving data"); 
                  },
          ()   => {
                    console.log( tempArray[0] );
                  }
        );
      }
    }