0
votes

I am trying get data back from a Angular 4 service after making a HttpClient post request, I can see that the data is coming back in the subscribe method, but I cannot pass it to the other variables in the method; Below is my code from the component calling the service:

=========Service Method ==============

autheticateUser(name: string, pass: string) {  
  const info: any = {};
  info.userName = name;
  info.password = pass;

  return this._http.post<Itoken>(this.url, info)
                   .shareReplay()
                   .do((data)=> {this.jwtToken = data;});
}

=============Component calling this service ==========

login() {
  this.flag = true;
  this.mode= 'indeterminate';
  this.authuser.autheticateUser(this.user.userName,this.user.password)
               .subscribe((data)=> {this.localtoken = data;});

   console.log(this.localtoken); // No value this.localtoken variable
2
Do your console.log inside the subscription.Currently you are trying to view what's in localtoken before it arrived - TheUnreal
thanks for the reply :) ; yes, I can see the data inside subscribe, but I want to use the data outside the subscribe method. How can I get the value back from the subscribe to other variable in the login method ? - user2741438
@user2741438 can you describe what you want to do with localtoken? We can suggest you a way to do the same. Also, let me tell you that there is no way to use localtoken outside the subscribe method inside the method that subscribe is called. - Arpit Sancheti
@jonrsharpe, I agree with you - Arpit Sancheti

2 Answers

1
votes

move your log inside the subscribe. for example code like this.

userResumeBio:any = [];

this.userresumeservice.getResume().subscribe((res: Response) => {
   console.log(res , 'User resume response');
   this.userResumeBio = res;
   console.log(this.userResumeBio , 'UserService userResumeBio response');
}, err=>console.log(err))
0
votes

.subscribe() is asynchronous. Thus you don't know when it will be triggered, and if you do stuff with the result outside the subscribe() (like your console.log()), this result may not be defined yet.

As @TheUnreal said, move your log inside the subscribe. That's how you want to use it :)