Issue
when i nagivate to another page in my IONIC app the api call (GET) dont work as intended, they need a token for authorization but on the first time i navigate to that page, the storage.get doesnt get the token in time. If then i go back to the homepage and return back again it works as intended.
ngOnInit(){
this.storage.get('token')
.then (result => this.token = result)
}
ionViewWillEnter(){
this.loadData()
}
async loadData(){
await this.getNotifications();
}
using console logs i see that the first time i navigate to the page the token is empty. Seems like the storage.get takes too much time and the api call is executed before i get the token. I tried with setting ngOnInit with async await it didnt work.
Solution
It seems like you're facing an issue with the timing of fetching the token from storage before making an API call. Since the storage.get
method is asynchronous, there's a chance that the API call is being executed before the token is retrieved. Here's a possible solution to ensure that the token is fetched before making the API call:
ngOnInit() {
this.fetchTokenAndLoadData();
}
async fetchTokenAndLoadData() {
try {
this.token = await this.storage.get('token');
if (this.token) {
await this.loadData();
} else {
console.log('Token not found');
}
} catch (error) {
console.error('Error fetching token:', error);
}
}
async loadData() {
try {
await this.getNotifications();
} catch (error) {
console.error('Error loading data:', error);
}
}
By using the async/await
syntax, you're ensuring that the token is fetched before attempting to load the data. If the token retrieval fails for any reason, you can handle the error appropriately. This way, you won't make the API call until you have a valid token.
Answered By - Ashish Mishra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.