How to detect a route change in Angular?

Web Development

I am looking to detect a route change in my AppComponent.

Thereafter I will check the global user token to see if he is logged in. Then I can redirect the user if he is not logged in.

1
Answers

Replies

Ans: The below has to be used.


this.router.events.subscribe((event: Event) => {})


Below is the example that is represented below.


import { Component } from '@angular/core'; 

import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';

@Component({

    selector: 'app-root',

    template: `<router-outlet></router-outlet>`

})

export class AppComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {

            if (event instanceof NavigationStart) {

                // To Show loading indicator

            }

            if (event instanceof NavigationEnd) {

                //To  Hide loading indicator

            }

            if (event instanceof NavigationError) {

                // To Hide loading indicator

               // To Present error to user

                console.log(event.error);

            }

        });

  }}

 


 


 


 


 


 


 

 
 

If you want to unleash your potential in this competitive field, please visit the Web Development course page for more information, where you can find the Web Development tutorials and Web Development frequently asked interview questions and answers as well.

 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
To Top