首页 > 解决方案 > CanLoad、Lazy 模块和 take(1)

问题描述

我正在使用 CanLoad 保护一个带有 Guard 的惰性模块。

我正在恢复我的 ngrx 商店的状态,并检查用户是否已通过身份验证。

这是我的 auth-guard.service.ts 中的代码:

canLoad() {
    return this.store.pipe(
        select('auth'),
        take(1),
        map(
            (authState: fromAuth.State) => {
                if (authState.authenticated) {
                    return true;
                } else {
                    this.router.navigate(['/auth/signin']);
                    return false;
                }
            }
        ))
}

这段代码没问题。一切都按预期工作。

但问题是......为什么我需要使用 take(1) 来使它工作?如果我删除了 take(1),这个守卫就不能正常工作。

标签: angularlazy-loading

解决方案


它只能与 take(1) 一起使用,因为此时没有 observable 将不会完成,并且 canLoad 等到 observable 完成。

请参阅http://reactivex.io/documentation/operators/take.html,take将从其源构建一个新的 observable take x 项目,完成后将忽略其他项目。


推荐阅读