Geoff
Geoff

Reputation: 6649

Accessing the result of a promise in angular2

Am new to angular2 and i would like to access the results of a promise but fails

This is what i have tried

In the authservice

token: string ;

 constructor( private _http: Http, private _storage: Storage) {

    this._storage.get('currentUser')
      .then(res=> this.token = JSON.parse(res).token)

       //WHEN I SET AN ARBITRARY VALUE IT RETURNS
          eg:this.token="dsd";

       //Also this logs a value
      // .then(res=> console.log(JSON.parse(res).token))

   }

In another componenet then i access the token by

authtoken: string;
constructor( private _authservice: AuthService, public _loadingCtrl: LoadingController) {
this.authtoken = this._authservice.token;
  }

  in the view
{{authtoken}}

What am i misssing

Upvotes: 1

Views: 88

Answers (2)

AVJT82
AVJT82

Reputation: 73377

Try this in service:

getToken() {
  return JSON.parse(this._storage.get('currentUser')).token;
}

and then in your component:

this.authtoken = this._authservice.getToken();

and if there is an async problem, it could be worth adding the elvis-operator in view:

{{authtoken?}}

Upvotes: 1

Batajus
Batajus

Reputation: 6277

Your second component does not know, when the asynchronus function call has finished. So you will get a null or undefined value as return value.

I would suggest something like this:

token: string ;

constructor( private _http: Http, private _storage: Storage) {

}

setCurrentUser(): Promise<void>{
    if (this.token == undefined ||this.token == ""){ //Only sets the token if no user is signed in
        return this._storage.get('currentUser').then(res=> this.token = JSON.parse(res).token)
   } 

   return Promise.resolve();
   //WHEN I SET AN ARBITRARY VALUE IT RETURNS
      eg:this.token="dsd";

   //Also this logs a value
  // .then(res=> console.log(JSON.parse(res).token))
}

And in your other component this:

authtoken: string;
constructor( private _authservice: AuthService, public _loadingCtrl: LoadingController) {

}

ngOnInit(){
    this._authservice.setCurrentUser().then(() => {
        this.authtoken = this._authservice.token;
    }
}

  in the view
{{authtoken}}

Upvotes: 1

Related Questions