我有一个布局组件,如下所示:
<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>
我有一个“激活”事件,应该在每次更改路线时检查“令牌”。
问题开始于localStorage中的令牌过期,并且在其对“ activate”事件进行更新之前,新页面上的另一个OnInit发布请求发送带有旧标题的请求,这会导致错误。
例如,我在家庭组件上具有此功能
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 => { });
并且因为标头使用了错误的令牌,所以请求失败。 我读了一些答案,并尝试与async await一起使用,但没有帮助
答案 0 :(得分:2)
您可以使用RouteGuard并调用API并返回true或false。
canActivate() {
// call API to validate Token
// If Validate token runs correctly return true
// else return false
}
请确保通过键 canActivate 将Guard包含在路由模块中 例子
{ path: 'home', component: HomeComponent, canActivate: [Guard] },