在 Angular 6 中通过 HttpClient 获取和存储 JSON 数据

Get and store JSON data via HttpClient in Angular 6

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

javascript 是异步的。在您向服务器发出请求后,您正在中间将数组第一个元素写入控制台,因此即使响应也不会收到。

所以试试这个:

  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?

我终于找到了解决办法。订阅函数有 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] );
              }
    );
  }
}