user2741438
user2741438

Reputation: 67

Angular 4 subscribe is not returning value

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

Upvotes: 0

Views: 3514

Answers (2)

Adil
Adil

Reputation: 629

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

Upvotes: 1

Brocodile
Brocodile

Reputation: 23

.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 :)

Upvotes: 0

Related Questions