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