Search code examples
angularangular-router-guards

Is it possible to guard a method in Angular?


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


Solution

  • 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/