在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] );
}
}
答案 0 :(得分:1)
我终于找到了解决方案。订阅功能具有3个参数,第二个和第三个是可选的。第二个参数是发生错误时的值,第三个参数是接收到所有数据时的值,此时我们可以打印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] );
}
);
}
}
答案 1 :(得分:-1)
javascript是asycnc。向服务器请求后,您将在中间将数组的第一个元素写入控制台,这样就不会收到响应。
所以尝试一下:
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] );
});
查看以下内容:How do I return the response from an asynchronous call?