【问题标题】:Angular 2 Auth Gaurd using ngrx store select. Do i unsubscribe?Angular 2 Auth Gaurd 使用 ngrx 商店选择。我要退订吗?
【发布时间】:2017-08-21 20:41:06
【问题描述】:

我在模板中为所有商店选择值使用异步管道,因为它自己完成所有清理工作,包括取消订阅。

但是当我手动订阅我的 auth gaurd 中的值时,我需要取消订阅吗?如果是,那么最好的方法是什么?

@Injectable()
export class AuthGaurd implements CanActivate{

constructor(
    private store: Store<fromRoot.State>,
    private router: Router
){}

canActivate(){
    this.store.select(getLoggedInState).subscribe(res => {
        if(res){
            return true
        }else {
            this.router.navigate(['/login']);
        }
    });
        return false;
    }
}

【问题讨论】:

  • 你没有取消订阅,你想做什么?
  • @Aravind 我在哪里退订?退订线会去哪里?
  • 你不应该订阅你的后卫,试试在 github 上发表评论。 github.com/ngrx/store/issues/270#issuecomment-260845982
  • @Adam 谢谢!!这太棒了!
  • 这并不意味着您可以对帖子投反对票

标签: angular observable ngrx unsubscribe


【解决方案1】:

您应该使用take 来获取第一个值:

canActivate(){
    this.store.select(getLoggedInState).take(1).subscribe(res => {
        if(res){
            return true
        }else {
           c this.router.navigate(['/login']);
        }
    });
        return false;
    }
}

take(n) 使 observable 获取它接收到的第一个 n 值,然后完成。在这种情况下,您无需取消订阅。

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 2017-07-30
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多