【发布时间】:2018-08-16 08:34:38
【问题描述】:
在 Angular 6 中,我想从 http://jsonplaceholder.typicode.com/todos 获取 JSON 数据(对象数组)并将它们存储到 tempArray。 我在箭头函数中做过,但是在箭头函数之后, tempArray 是未定义的。
例如,当我想通过 console.log() 打印 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]);
});
console.log( tempArray[0] );
}
}
【问题讨论】:
-
首先,您需要服务中的 http 内容,而不是组件。其次,console.log 将在订阅完成之前触发
标签: arrays json angular arrow-functions angular-httpclient