首页 > 解决方案 > 使用带有 rxjs 的 Vue-router 保护?

问题描述

我想保护我的一些路线。

例如像这样

{
   path: 'guardedPath',
   component: GuardedComponent,
   meta: {requiresAuth: true}
  }

然后在 beforeEach 中,我使用了警卫类的方法

router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.requiresAuth)) {
        if(!guard.guarded()) {} else {next()}
    }
})

我有一门课,我从三个变量中生成一个 Observable。

import { Observable } from 'rxjs/Observable';

import 'rxjs/operators/combineLatest';

export class ConfigService {
    constructor() {}

    checkConfig() {
        let storedVar = this.store.state.storedVar;
        let savedVar = this.anotherService.getValue('string1');
        let anotherSavedVar = this.anotherService.getValue('string2');

        return Observable.combineLatest(storedVar, savedVar, anotherSavedVar);
    }
}

storedVar是 的true/falsestoresavedVar并且anotherSavedVarObservables

在那之后,在我的警卫班中,我正在使用这种方法。我想combineLatest根据返回值映射值返回true或调用falsein 方法。beforeEach

import 'rxjs/add/operator/map';

export class Guard {
    constructor() {}

    guarded() {
        return this.configService.checkConfig().map((data) => {
            console.log(data);
        });
    }
}

问题是地图运算符不运行。功能本身正在工作,但data不是来自Observable.

标签: vue.jsrxjs

解决方案


Observable是惰性数据结构。您需要实际订阅Observable它才能执行任何操作。

很可能你想要更像这样的东西

export class Guard {
    constructor() {}

    guarded() {
        return this.configService.checkConfig()
          .map(data => /* Do Some transform logic here */ return data)
    }
}

router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.requiresAuth)) {
        // Subscribe to the result of the guard and process
        // the handler in the callback function.
        guard.guarded().subscribe(guardResult => {
          next(guardResult.allow ? undefined : {name: 'Unauthorized'});  
        })
    }
})

推荐阅读