Angular get current route defined, than undefined

832 Views Asked by At

I have this code:

import { Router } from '@angular/router';

Then:

constructor(router: Router) {
    console.log(this.router.url);
}

When I load the page, it will first tell me the URL is "/"

Unhandled Promise rejection: Error in ./BaPageTop class BaPageTop - inline template:22:4 caused by: Cannot read property 'url' of undefined ;

I want to check if the current URL is equal to /login, and otherwise redirect to "/login" in the constructor. I tried doing this with window.location.href but it doesn't work because the URL is not changing parhaps?

1

There are 1 best solutions below

0
On

Based on your constructor code, you never set this.router to anything, so it will always be undefined. By default, when you pass a parameter into a constructor, it does NOT become a property of this. You should change your code to:

constructor(router: Router) {
    console.log(router.url);
}

Alternatively, if you really want to use this.router (for example if you want to use the router in other functions in the same class), you can use the public or private keywords when you declare the parameter:

constructor(private router: Router) {
    console.log(this.router.url);
}