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] );
}
}
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] );
}
);
}
}