0

I have a variable token in my service. At the moment, it governs whether I'm authenticated or not. When the application needs to chck if the user is signed in, it asks the app !!this.security.token and reacts accordingly. That needs to occur in every secured component.

ngOnInit() {
  if (!this.security.token)
    this.router.navigate(["/login"]);
  ...
}

I wonder if there's a better method handling this. I'm comparing the HTTP interceptor that adds headers and logging to my GETs and POSTs, which is mighty convenient. However, googling interceptor angular router gave only hits on HTTP injecting, nothing about controlling the routing.

Is there a way to intercept the call to each component checking that token still exists?

export class SomeComponent implements OnInit {
  constructor(
    private security: SecurityService,
    private router: Router,
    private route: ActivatedRoute) { }

  id: string;

  ngOnInit() {
    if (!this.security.token)
      this.router.navigate(["/"]);

    this.route.params
      .subscribe(suc => this.id = suc.id);
  }
}
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • 1
    https://angular.io/guide/router#milestone-5-route-guards – JB Nizet Dec 15 '19 at 11:02
  • Angular Provides Route Guards to protect your components – YogendraR Dec 15 '19 at 11:05
  • @JBNizet Aha, my ignorance was at blame here. Once I used *guard* intead of *interceptor*, the list of findings was much more adequate. Thanks! Interesting that Angular team used two different names for the same concept (well, "the same'ish"). – Konrad Viltersten Dec 15 '19 at 12:32

1 Answers1

1

As previously mentioned by others, Angular provides route guard to check if a particular user is enabled or not to navigate on that route.

You can also implement your custom validation on your routes.

StackBlitz example

Random blog example

Convenience example

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
Fmerco
  • 1,160
  • 5
  • 20