【问题标题】:Http get service not able to assign result to variableHttp获取服务无法将结果分配给变量
【发布时间】:2019-06-08 03:10:05
【问题描述】:

使用以下服务将结果设置为this.temp,控制台日志在订阅内显示结果,但在订阅外返回未定义。

   1) this.http.get('../../assets/students.json').subscribe((data)=>{
   2)   this.temp = data;
   3)   console.log(data);//shows result
   4)   console.log(this.temp);//shows result
   5) })
   6) console.log(this.temp);//undefined

但是在控制台行中,是先输出6,再输出3和4

【问题讨论】:

标签: angular http


【解决方案1】:

发生这种情况是因为 Angular 中的 http 调用是通过 observables 实现的,它将在未来的某个时间点评估 asycn。现在,如果你想对数据或 this.temp 做一些事情,你必须在 subscribe 调用中做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2020-02-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多