Angular将响应数据保存到变量中

问题描述 投票:0回答:2
user: User

this.httpService.getCurrentUser()
.subscribe(
    data => {
      this.user = JSON.parse(data["_body"]).value[0];
          console.log("1" +this.user)
         },
   error => console.error(error)
     );
console.log("2"+this.user);

所以在这个函数中我得到了我的currentUser并把它放到我的变量中,如果我第一次记录我的this.user它有正确的信息,但是在第二个日志中它只是说[object] [object]但为什么呢?似乎响应数据仅在该函数期间存在于变量中,但稍后会丢失

angular http httpresponse
2个回答
0
投票

通过使用console.log("2"+this.user);,你告诉Javascript将this.user对象首先转换为字符串(这是[object Object]),然后与2连接。

还记得console.log(2...)将首先发生。因为console.log(1...)将在从服务器获取数据后发生。

此外,我看到你正在将服务器的响应分配给this.User,而你正在打印this.user - 注意首都U.

我的猜测是你从服务器加载一个对象。只需使用console.log(this.user)即可获得响应。


0
投票

您需要记住,您拥有的任何订阅都是异步代码。

this.httpService.getCurrentUser()
.subscribe(
    data => {
        // This may or not (probably not) run first
      },
   error => console.error(error) // This may never run, if error doesn't occurs.
     );

// This will run after the subscription is made. Almost always before the success callback.
console.log("2"+this.user);

任何依赖于HTTP请求等异步响应的东西都应该在其中。

© www.soinside.com 2019 - 2024. All rights reserved.