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?
Based on your constructor code, you never set
this.router
to anything, so it will always beundefined
. By default, when you pass a parameter into a constructor, it does NOT become a property ofthis
. You should change your code to: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 thepublic
orprivate
keywords when you declare the parameter: