implementing canActivate auth guard in angular

后端 未结 1 476
说谎
说谎 2021-01-17 05:50

I have a service with this function that returns true or false on rather or not a token is valid

loggedIn() {
return this.http.get(\'http://localhost:3000/us         


        
相关标签:
1条回答
  • 2021-01-17 06:03

    The canActivate function must return a boolean, a promise of a boolean, or an observable of a boolean.

    In your case, you return nothing. Probably because you ommited the return in your function.

    But it wouldn't work if you add it, because then, you would return a subscription, which isn't accepted by the signature.

    What you could do is this :

    canActivate() {
      return this.authService.loggedIn().map(res => {
        if(!res) {
          this.router.navigate(['/login']);
        }
        return res;
      });
    }
    

    With this code, you comply with the signature, and keep your routing logic.

    0 讨论(0)
提交回复
热议问题