Reputation: 313
I have a layout component which look like this :
<div class="wrapper" style="display: flex; flex-direction: column; padding: 0" >
<app-header style="flex: none;"></app-header>
<div style="flex: 1 0; position: relative;">
<router-outlet (activate)="onActivate()" ></router-outlet>
<app-footer *ngIf="showFooter"></app-footer>
</div>
</div>
I have an "activate" event which should check the 'token' every route changing.
The problem start when token in the localStorage is expired and before its update him on the "activate" event another OnInit post request on the new page send a request with the old header which cause an error.
For example I have this function on my home-component
this.serverRequest.getTrainingsFromTo(weekBoundry.from.getTime(), weekBoundry.to.getTime()).subscribe((trainings: ITrainingInfo[]) => {
console.log(`trainings : ${trainings}`)
if (trainings) {
// Ensure server sent just this week's trainings
var filteredTrainings: ITrainingInfo[] = trainings.filter((ti) => {
return ti.finishTime >= weekBoundry.from.getTime() && ti.finishTime < weekBoundry.to.getTime();
});
filteredTrainings.forEach((ct: ITrainingInfo) => {
var index: number = new Date(ct.finishTime).getDay();
this.weekDaysWithTrainings[index] = true;
this.trainingsThisWeek = this.weekDaysWithTrainings.reduce(function (total, x) { return x == true ? total + 1 : total }, 0)
});
}
}, error => { });
And because the header is with a wrong token , the request failed. I read a few answers , and tried to work with async await but nothing helped
Upvotes: 0
Views: 328
Reputation: 203
You can use RouteGuard and call API and return true or false.
canActivate() {
// call API to validate Token
// If Validate token runs correctly return true
// else return false
}
Make sure to include Guard to route module as well with key canActivate Example
{ path: 'home', component: HomeComponent, canActivate: [Guard] },
Upvotes: 1