【问题标题】:Wait for observable on component to finish on another component等待组件上的 observable 在另一个组件上完成
【发布时间】:2019-12-12 23:47:26
【问题描述】:

我有一个布局组件,如下所示:

<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 中的令牌过期时问题开始,并且在它更新他之前的“激活”事件之前,新页面上的另一个 OnInit 发布请求发送一个带有旧标头的请求,这会导致错误。

例如,我的 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 => { });

并且由于标头带有错误的令牌,因此请求失败。 我阅读了一些答案,并尝试使用 async await 但没有任何帮助

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    您可以使用RouteGuard并调用API并返回true或false。

    canActivate() {
        // call API to validate Token
       // If Validate token runs correctly return true
       // else return false
    
    }
    

    确保包含 Guard 到路由模块以及密钥 canActivate 示例

    { path: 'home', component: HomeComponent, canActivate: [Guard] },
    

    【讨论】:

    • 谢谢,但是我怎样才能从 observable 中返回答案给 canActivate 函数呢?
    • 您可以创建一个主题并从 CanActivate 发出它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多