-1

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?

Arnold
  • 175
  • 12
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – Roman C Feb 20 '17 at 10:23
  • You need to use `router.events.subscribe(...)` and read the URL **after** the first navigation happened. – Günter Zöchbauer Feb 20 '17 at 10:25
  • Okey, I will change the question – Arnold Feb 20 '17 at 10:25

1 Answers1

1

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);
}
AJ Richardson
  • 6,610
  • 1
  • 49
  • 59