AntonBoarf
AntonBoarf

Reputation: 1313

Angular - how to "exit" a component?

Let's imagine I have a component that requires authentification (in fact some instance of that component need an authentication, other do not depending on "id" route instance variable) :

ngOninit() {
const id = +this.activatedRoute.snapshot.params.id;
this.isSecured = requiresAuthentication(id);

if (this.isSecured && !this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
}

//very private data loading code

The problem is the rest of my code is always executed (which is fine if this component isn't secured or the user is logged in). But when the "if" condition is true (when navigate to login page), the rest of my code in the ngOninit() method still executes.

Upvotes: 1

Views: 3753

Answers (2)

Withtaker
Withtaker

Reputation: 1884

if(this.isSecured && this.authService.isLoggedIn()) {
  // sensitive stuff
} else {
this.router.navigate(['/login']);
}

Upvotes: 1

user9975674
user9975674

Reputation:

The problem is in your pattern to validate the session or authentication of a user. The ideal pattern proposed by Angular is not to assemble the components if the access condition is not met.

For example:

class UserToken {}
class Permissions {
  canActivate(user: UserToken, id: string): boolean {
    return true;
  }
}

@Injectable()
class CanActivateTeam implements CanActivate {
  constructor(private permissions: Permissions, private currentUser: UserToken) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    return this.permissions.canActivate(this.currentUser, route.params.id);
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        canActivate: [CanActivateTeam]
      }
    ])
  ],
  providers: [CanActivateTeam, UserToken, Permissions]
})
class AppModule {}

Upvotes: 2

Related Questions