Reputation: 73
I am trying to set the token i have stored in the storage module of Ionic, to a public variable so i can call it later in the file, however when i try and set it and then call the variable from a different function i get a undefined error
code
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Component, Injectable} from '@angular/core';
import { Storage } from "@ionic/storage";
import 'rxjs/add/operator/map';
@Injectable()
@Component({
providers: [HttpClient]
})
export class DataProvider {
public token:string;
constructor(public http: HttpClient, public storage: Storage) {
}
authToken(){
console.log('token function')
this.storage.get('token').then((val) => {
this.token = val;
console.log(this.token);
});
}
getsomething(){
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.authToken();
console.log(this.token);
}
}
Upvotes: 0
Views: 881
Reputation: 4522
It will be because the token is being read from storage using a promise, so when read in authToken
the promise has resolved, but in getsomething
you are trying to log the token before it has been set in the promise.
To be sure you have the token in getsomething
you will need to return the promise from authToken
authToken(){
console.log('token function')
return this.storage.get('token').then((val) => {
this.token = val;
console.log(this.token);
});
}
getsomething(){
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.authToken().then(() => {
console.log(this.token);
})
}
Upvotes: 0
Reputation: 6421
You need authToken()
to return a promise, since it's asynchronous your getSomething()
will execute authToken()
and will not wait for it to finish to execute the following console.log(this.token)
, that's why it's coming as undefined. There's a couple ways you can work this out:
1 - Just get your token inside of your getsomething()
getsomething(){
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.storage.get('token').then((val) => {
this.token = val;
console.log(this.token);
// THE REMAINING CODE YOU NEED TO EXECUTE
});
}
2 - authToken()
returns a promise
authToken = (): Promise<any> => {
console.log('token function')
return new Promise<any>(res => {
this.storage.get('token').then((val) => {
this.token = val;
console.log(this.token);
res(val);
});
});
}
getsomething(){
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
this.authToken().then(res => {
console.log(this.token);
});
}
3 - Get your token in your constructor (if you've already saved it before)
constructor(public storage: Storage){
this.storage.get('token').then((val) => {
this.token = val;
console.log(this.token);
});
}
Hope this helps.
Upvotes: 1