【问题标题】:Get and store JSON data via HttpClient in Angular 6在 Angular 6 中通过 HttpClient 获取和存储 JSON 数据
【发布时间】: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] );
  }
}

【问题讨论】:

标签: arrays json angular arrow-functions angular-httpclient


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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?

    【讨论】:

    • data.slice() 无法正常工作,因为 Data 的类型为 Object 而不是 DataResponse/DataResponse[]
    • 其实不用.slice(),`tempArray = data`就可以了。
    • 另外问题不是.slice(),问题是异步编程。
    • 感谢您的反馈。我正在努力帮助人们。实际上,没有必要投票反对,如果您也想帮助人们,您可以编辑答案。
    • 投反对票的人显然和我一样认为,你不能对对象进行切片并且你没有进行类型转换。就最佳实践而言,这个答案也不是最好的
    猜你喜欢
    • 2023-04-03
    • 2019-03-19
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多