2

I was wondering if it's possible to guard a method in an Angular app instead of a route. Let's say you have a button, if you click it and are not logged in, you would be redirected to the login page.

thanks

Remaori
  • 95
  • 1
  • 9

1 Answers1

1

There are no such guards for methods. Instead, the most possible solution for you is to create a conditional check in the method you would like to protect.

For example, if the method that needs to be protected is checkoutCart() and you have a service in your angular application that informs you if the user is logged in or not. Then this is what you can do inside your checkoutCart() method:

checkoutCart() {
   if ( !this._authenticationService.isLoggedIn ) {
      this.router.navigate(['/', 'login']).then(nav => {
         console.log(nav); // true if navigation is successful
      }, err => {
         console.log(err) // when there's an error
       });

      return;
   }

   // REST OF YOUR PROTECTED CODE
}

To learn how the router works you can take reference from: https://alligator.io/angular/navigation-routerlink-navigate-navigatebyurl/

Tofiq Quadri
  • 379
  • 5
  • 16
  • 1
    Thanks, that's what I was thinking. I'm basically trying to do the same thing as google do with google books. When you want to add a book into you bookshelf and are not connected, you are being redirect to login page. The button is here even if you're not connected. – Remaori Mar 23 '20 at 06:03