我正在使用 @ngrx/store 来检查状态是否已经加载,并且我遇到了一个问题,即canActivate
如果我使用过滤器,该方法永远不会返回。
这是 GetCompanies 操作的示例效果:
return this.companiesService.getCompanies()
.pipe(
map(companies => new companiesActions.GetCompaniesSuccess(companies)),
catchError(error => Observable.of(new companiesActions.GetCompaniesFail(error)))
)
如果出现错误,我将发送 GetCompaniesFail 操作并将用户重定向到/login
页面。没关系,有趣的部分是守卫。
@Injectable()
export class CompaniesGuard implements CanActivate {
constructor(
private store: Store<AppState>,
private router: Router
) {}
canActivate(): Observable<boolean> {
return this.checkStore()
.pipe(
switchMap(() => Observable.of(true)),
catchError(() => Observable.of(false))
);
}
checkStore(): Observable<boolean> {
return this.store.select(getCompaniesLoaded)
.pipe(
tap(loaded => {
if (!loaded) {
this.store.dispatch(new companiesActions.GetCompanies());
}
}),
filter(loaded => loaded),
take(1)
);
}
}
如果出现错误并且加载不为假,则canActivate
不会返回任何内容,因为checkStore
什么也不做。
如果我更改filter
为map
它可以工作,但它只需要第一个值,false
即使数据将成功加载。
我错过了什么?我该如何处理那里的 HTTP 错误?有没有办法等待特定状态或在内部抛出错误checkStore
?
预先感谢!