这是我的警卫
import { Injectable} from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanLoad,
Route
} from '@angular/router';
import { Observable, of } from 'rxjs';
import { switchMap, map, filter, take, tap, catchError } from 'rxjs/operators';
import { Store} from '@ngrx/store';
import * as fromStore from '../store';
@Injectable({
providedIn: 'root'
})
export class AuthenticationGuard implements CanLoad {
constructor(
private store: Store<fromStore.State>
) {}
canLoad(route: Route): boolean | Observable<boolean> | Promise<boolean> {
return this.store.select(this.store.getUser).pipe(
tap(user => {
if (!user.loaded) {
console.log('loading user');
this.store.dispatch(new fromStore.LoadUser());
}
}),
filter(user => user.loaded),
map(user => {
console.log('User loaded get rights', user);
return this.hasRights(user, route);
}),
catchError(error => {
console.log(error);
return of(false);
}),
take(1)
);
}
hasRights(user, route: Route): boolean {
if (!user.loaded) {
return false;
} else {
console.log('returning true');
return true;
}
}
}
运行此防护后,其作用就好像选择器尚未完成,但是我在“正在加载用户”上获取日志,然后在“用户已加载获得权限”上获取日志,然后得到“返回真实”日志。 。作为最后一步,我还添加了take(1),但它的行为仍然像可观察对象无法完成我所缺少的吗?