首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当尝试检索和映射Angular 6中的JSON数据时,控制台输出显示为"undefined“

当尝试检索和映射Angular 6中的JSON数据时,控制台输出显示为"undefined“
EN

Stack Overflow用户
提问于 2018-08-05 00:42:26
回答 1查看 227关注 0票数 -1

我正在尝试学习如何从api获取JSON数据,将其解析并映射到我的类型,然后将其显示在angular material datatable中。但是,当我检查我的控制台输出时,它显示该值为undefined。我甚至还没有创建datatable。

有没有人能告诉我我哪里错了?我使用的是Angular 6.1.0:

代码语言:javascript
复制
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from '../../node_modules/rxjs';    

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  title = 'NgTable';
  myPlace = "https://jsonplaceholder.typicode.com/posts";  
  myPosts: Observable<posts[]>;  
  myPostArr: posts[];

  constructor(http: HttpClient){
    this.myPosts = http.get<posts[]>(this.myPlace);
    this.myPosts.subscribe(response => {this.myPostArr = response});

    console.log(this.myPostArr);
  }
}

export interface posts {
  userId: number;
  id: number;
  title: string;
  body: string;
}

console.log的输出为:未定义

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-05 00:49:23

由于observable的异步特性,this.myPostArr在某个时间点获取数据,因此,在subscribe块之外,它不会在该行执行时被解析。

我会建议你把所有的http方法放在一个服务中,然后返回Observables

代码语言:javascript
复制
constructor(http: HttpClient){
    this.myPosts = http.get<posts[]>(this.myPlace);
    this.myPosts.subscribe(response => {this.myPostArr = response;

    console.log(this.myPostArr);
});
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51687641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档