Apologies for the rookie mistake, I am currently transitioning from a C# background to Ionic, which may be causing some confusion on my end. I'm working on retrieving a stored token from Ionic storage but I'm struggling with understanding promises and .then method, so I decided to use 'await' since it's more familiar to me from C#.
This is a snippet from the Api Service TS file that I'm trying to build:
export class ApiService {
ServerUrl = environment.url;
BearerToken: string;
GetUserDetailsEndPoint = 'api/Account/GetUserDetails';
UpdateUserDetailEndPoint = 'api/Account/UpdateUserDetail';
TokenEndPoint = 'Token';
RegisterEndPoint = 'api/Account/Register';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'bearer ' + this.BearerToken
})
};
constructor( private http: HttpClient,
private storage: Storage,
private alertController: AlertController ) {
this.getBearerToken();
console.log('Have awaited the token and its value is:' + this.BearerToken);
}
async getBearerToken() {
this.BearerToken = await this.storage.get(TOKEN_KEY);
}
However, the 'this.BearerToken' ends up being undefined when logged to the console. (The value does exist in the store). It seems like an asynchronous issue, but I can't figure out why 'await' isn't working. Most resources refer to using .then with promises. What am I missing here? Thanks
EDIT Following advice from Igor, I moved the initialization out of the UserService and into the ngOnInit of my menu page where I need to first use it. Despite focusing on getting user info instead of the token from local storage, I'm encountering the same issue. There's a function to get the stored user data:
async getUserStore() {
this.data = await this.storage.get(USER_DATA);
console.log('getUserStore: email = ' + this.data.Email);
}
The above function still returns a promise without waiting. Do I need to return something specific to make await actually wait? e.g.
return await this.storage.get(USER_DATA);
Or should I use the .then approach? And if so, what’s the point of 'await' then?
My calling function looks like this to work as expected:
ngOnInit() {
this.user.getUserStore().then(() => {
console.log('ngOnInit - menu page, this.user email is: ' + this.user.data.Email);
if (this.user.data && !this.user.data.DetailsComplete) {
this.showAlert('Your Details are incomplete, please complete them.');
}
console.log('ngOnInit - menu page');
});
}
With the await in the async function, I would expect it to look like this (which doesn’t work):
ngOnInit() {
this.user.getUserStore();
console.log('ngOnInit - menu page, this.user email is: ' + this.user.data.Email);
if (this.user.data && !this.user.data.DetailsComplete) {
this.showAlert('Your Details are incomplete, please complete them.');
}
console.log('ngOnInit - menu page');
}
How can I make it actually wait in the called function using await? Or is it not possible? Thank you