vue.js - 使用带有 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/false
值store
,savedVar
并且anotherSavedVar
是Observables
。
在那之后,在我的警卫班中,我正在使用这种方法。我想combineLatest
根据返回值映射值返回true
或调用false
in 方法。beforeEach
import 'rxjs/add/operator/map';
export class Guard {
constructor() {}
guarded() {
return this.configService.checkConfig().map((data) => {
console.log(data);
});
}
}
问题是地图运算符不运行。功能本身正在工作,但data
不是来自Observable
.
解决方案
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'});
})
}
})
推荐阅读
- javascript - 根据最新的cookie,做一些事情
- react-native - React Native - componentDidUpdate 导致应用程序运行缓慢
- html - 导航项不在同一行
- python - 尝试使用 Gmail 或 Outlook 通过 python 发送电子邮件
- ruby-on-rails - 未定义的方法“relation_delegate_class”
- google-cloud-platform - Google Cloud DNS 访问我的服务器
- javascript - 动态分配内存(在运行时声明变量)时,JavaScript 中的提升如何工作?
- python - 如何使用 pyMongo 从 MongoDB“流式传输”数据?
- apache-kafka - 如何实现使用 kafka 代理和用户名和密码但不使用 ssl 证书的骆驼 kafka 生产者和消费者
- java - 如何搜索存储在列表中的句子
在文件中(Java)