Sreemat
Sreemat

Reputation: 626

Calling observable function in same class in angular2

I have two function in a class where

First function returns Observable.

Second function is called from other component

I want call first function in second use the value of first and process it.

Sample code:

@Injectable()
export class SampleService {

service:string;

getService(): Observable<any> {
        return this._http.get(`url`, {
            headers: this.headers()
        }).map(res=>res.json();)
            .catch(err=>console.log(err);
    }
 }


generateToken():string{
const service="";
this.getService().subscribe(res=>{service=res});
//process it
return service;
}

Whenever i call the second function the value of service is return as empty.How to await till the subscribe is over and then process.

Upvotes: 0

Views: 3359

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657348

You can't return a value that you get from an observable.

You can either use map in the 2nd method as in the first method and then subscribe where you call generateToken

generateToken():string{
  return this.getService().map(res=>{return service=res});
}

someMethod() {
  this.generateToken.subscribe(res => this.service = res);
}

or assign it to a field in the 2nd property

generateToken():string{
  return this.getService().subscribe(res=>{this.service =res});
}

update

someMethod() {
  this.generateToken.subscribe(res => {
    this.service = res;
    // other code here
  });
}

Upvotes: 1

chrispy
chrispy

Reputation: 3612

This will return asynchronously because the subscribe will not come back until it receives a response:

generateToken():string{
    const service="";

    this.getService().subscribe(res=>{service=res}); //Async

    return service; //Instant return of blank value
}

I would suggest returning the observable itself and subscribing to it where you need it:

generateToken(){
    return this.getService().map(res => res.json()); //presuming json payload
}

Then inside your components after requesting sampleService in constructor:

this.sampleService.generateToken().subscribe(data = > { //use data });

Upvotes: 0

Related Questions