首页 > 解决方案 > 将 Json 数据检索到 ITest

问题描述

目标:
从json中获取数据到“test: ITest[];” 然后使用 console.log 显示它

问题:
代码不起作用。我错过了什么?

信息:
我是 Angular 的新手

谢谢!


服务

  getData2(): Observable<ITest[]> {
    return this.http.get<ITest[]>('https://api.github.com/users/hadley/orgs');
  }

export interface ITest {
  login: string,
  node_id: string
}

零件

  public test: ITest[];

  ngOnInit() {
    this.getData2()
  }


  getData2() {
    this.asdfService.getData2().subscribe(res => { this.test = res });

    console.log(this.test)
  };
export interface ITest {
  login: string,
  node_id: string
}

标签: angularvisual-studio-code

解决方案


你的方法getData2返回一个 Observable,它可能会在一段时间后被解析,但console.log调用是在 之后subscribe,所以当console.log被调用时,Observable 可能还没有解析。

试试这个:

  getData2() {
    this.asdfService.getData2().subscribe(res => { 
        this.test = res
        console.log(this.test)
    });  
  }

这样,您只有console.log在获得新值时才调用this.test


推荐阅读