1

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

但是当我手动订阅我的 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;
    }
}
4

1 回答 1

5

您应该使用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它接收到的第一个值,然后完成。在这种情况下,您无需取消订阅。

于 2017-03-28T17:16:37.850 回答