Konrad Viltersten
Konrad Viltersten

Reputation: 39148

Forcing a navigation in every ngOnInit (conditionally and implicitly) in Angular 8

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);
  }
}

Upvotes: 0

Views: 49

Answers (1)

Fmerco
Fmerco

Reputation: 1206

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

Upvotes: 1

Related Questions