【问题标题】:retrieve the Json data to the ITest将 Json 数据检索到 ITest
【发布时间】:2019-06-16 20:04:50
【问题描述】:

目标:
从 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
}

【问题讨论】:

  • 你能显示组件的完整代码吗? (不是 HTML,只是类)
  • 另外,当您说The code doesn't work. 时,发生了什么?有编译错误吗?运行时错误?没有视觉反馈?
  • 将您的console.log() 移入 传递给subscribe() 的回调函数。 http 请求是异步的。您不能指望在您发送请求后立即获得响应。它只会在以后可用,然后会调用回调。

标签: angular visual-studio-code


【解决方案1】:

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

试试这个:

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

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

【讨论】:

  • 是不是因为我用了 Observable 才必须在 subscribe 里面写 this.test ?
  • 执行getData2后,我还会从this.test获取数据吗?对我来说,它看起来像是空的?
  • 由于 Observables 使您的代码异步,因此您需要在 subscribe 内分配该变量,并且还需要在那里打印变量的值。关于第二个问题,不保证this.test在执行getData2后会有值,原因是代码是异步的:只有当传递给subscribe的函数被执行时,你才会有一个值多变的。我认为值得一读:angular.io/guide/observables
【解决方案2】:

欢迎使用 Angular。您的代码唯一的问题是

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

    console.log(this.test)
  };

应该是这样的

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

订阅中的代码被异步调用,因此如果您不将console.log 放入订阅中,它不会等待this.test = res 执行。这称为反应式编程,它是 Angular 的基本构建块。

this 是一个很好的起点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2010-11-30
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多