简体   繁体   中英

Angular save response data into variable

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);

So in this function I get my currentUser and put it into my variable and if i log my this.user the first time it has the correct information in it but on the second log it only says [object][object] but why? It seems like the response data is only in the variable during that function but lose it later

By using console.log("2"+this.user); you tell to Javascript to convert that this.user object first to string (which is [object Object] ) and then do concat with 2 .

Also remember that console.log(2...) will happen first. Because the console.log(1...) will happen AFTER fetching data from server.

Also I see you are assigning the response from server to this.User while your are printing out this.user - notice the capital U.

My guess is that you load an object from the server. Just use console.log(this.user) to what is the response.

You need to have in mind that any subscription that you have, is an asynchronous code.

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);

Anything that depends on a async response like an HTTP request, should be inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM