【问题标题】:Supscription in canload guard Angular2+canload guard Angular 2中的订阅
【发布时间】:2020-04-14 17:16:45
【问题描述】:

我正在尝试在 canload 防护中使用 combineLatest,但它得到了这个错误:类型 'Subscription' 缺少来自类型 'Observable' 的以下属性:_isScalar、source、operator、lift 和另外 6 个。

我的代码如下:

canLoad(route: Route): Observable<boolean> {
        return combineLatest(this.router.events, this.resources$, this.role$)
            .subscribe(([nav, res, role]) => {
              // some logic
                return false;
            })
 }

我想监听路由事件并通过路由 slug 检查权限。有人可以帮我吗?

【问题讨论】:

  • Lievno 是对的,你需要返回 Observable,而不是 Subscription。

标签: javascript angular rxjs guard


【解决方案1】:

您不必subscribe 只需返回combineLatest

Observable 之外的方法,但您返回Subscription

canLoad(route: Route): Observable<boolean> {
        return combineLatest(this.router.events, this.resources$, this.role$)
               .pipe(
                   // take the first value emitted and complete
                   first()
                   map((value) => {
                       if(value) {
                           return true;
                       }
                       return false;
                   })
               )
}

【讨论】:

  • 我试过了,但是还有一个问题,模块没有加载。我使用延迟加载
  • 在我的应用路径中:{ path: 'campaigns', canLoad: [PermissionGuard], loadChildren: () =&gt; import('@pages/campaign-page/campaign-page.module').then(m =&gt; m.CampaignPageModule) },
  • 但只有当 canLoad 返回 observable 时才会发生,如果我只返回 True 或 False,它工作正常
  • 您是否在与 observable 的逻辑部分之后返回了一个布尔值并确定您的 observable 已完成?
  • 我在 map 之后找到了 first() 运算符的解决方案
猜你喜欢
  • 2018-05-25
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 2016-10-09
  • 2018-06-12
  • 2018-08-08
  • 2018-04-24
  • 2021-05-06
相关资源
最近更新 更多