[英]angular guard with angular-redux/store
I'm using @angular-redux/store in my project.我在我的项目中使用@angular-redux/store 。 I'm trying to create a guard with @select()
decorator like this:我正在尝试使用@select()
装饰器创建一个警卫,如下所示:
@select((s: IAppState) => s.user.userInformations.userState) userState$: Observable<number>;
and my canActivate method is like this :我的 canActivate 方法是这样的:
canActivate(route, state: RouterStateSnapshot): Observable<boolean> {
return this.userState$.pipe(map(value => {
if (value === 0)
return false;
return true;
}));
}
What is the problem?问题是什么? the userState$ always returns default value.(lets say undefined) userState$总是返回默认值。(假设未定义)
What I tried so far?到目前为止我尝试了什么? I tried to filter Observable like this:我尝试像这样过滤 Observable:
this.userState$.pipe(skipWhile(val => val === undefined)).subscribe(value => {
console.log('value', value);
});
it works fine and return value is what I expected (in constructor).它工作正常,返回值是我所期望的(在构造函数中)。 but I can't use this in canActivate
method.但我不能在canActivate
方法中使用它。 I don't know what is the best way to map data in canActivate
.我不知道在canActivate
映射数据的最佳方法是什么。
Briefly: I'm looking for a way to skip first value of state (the initial value) and use it in canActivate
method as an Observable<boolean>
.简而言之:我正在寻找一种方法来跳过状态的第一个值(初始值)并在canActivate
方法中将其用作Observable<boolean>
。
PS it would be better if I could config @angular-redux/store to skip undefiend/initialed value in @Select() decorator by default. PS如果我可以配置@angular-redux/store默认跳过 @Select() 装饰器中的 undefiend/initialed 值会更好。
Thanks for your helps.感谢您的帮助。
I found the solution!我找到了解决方案!
We can use Promise
to fix that.我们可以使用Promise
来解决这个问题。 And since Promise
doesn't return Observable
, we should use from
from rxjs.由于Promise
不返回Observable
,我们应该使用from
from rxjs。 the final code is like this:最终的代码是这样的:
@select((s: IAppState) => s.user.userInformations.userState) userState$: Observable<number>;
userStatePromise = new Promise((resolve, reject) => {
this.userState$.subscribe(val => {
if (val !== undefined) {
resolve(val)
}
}, (err) => {
reject(err)
})
})
canActivate(route, state: RouterStateSnapshot): Observable<boolean> {
return from(this.userStatePromise).pipe(map(val => {
if (val === 0) {
// route anywhere you want
return false;
}
return true;
}))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.