jmona789
jmona789

Reputation: 2839

Angular 2 this.router.events.subscribe does not work on refresh or when url is typed in

I have an app written in Angular 2, the nav is supposed to look slightly different on each route. I am listening for NavigationEnd using this.router.events.subscribe It works fine when clicking links, but this method does not seem to be fired when the page is refreshed or when you type a route into the url bar.

This is part of my subscribe function:

subscribeToEvents() {
    this.router.events.subscribe((val) => {
        // see also 
        if (val instanceof NavigationEnd) {
            this.getCompanyName();
            var rou = val.url.toLowerCase().trim();
            console.log("our route", rou);
            switch (rou) {
                case "/projectlist":
                    this.currentPage = "projects";
                    this.page = "Project List";
                    break;

I have tried console logging this.router.url to see what comes up and it just always console logs '/' when I refresh the page.

Upvotes: 2

Views: 5076

Answers (3)

Ravi Anand
Ravi Anand

Reputation: 5514

The navigationEnd event has already been raised when the component registers for it under the parent/base component. This led the current component route instance not to publish another navigationEnd event. So the solution here is to explicitly start the subscription of the latest navigationEnd event by using the startWith() operator from the RxJs. i.e.

public myRouterObservable$ = this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    startWith(this.router),
    map((navigationEnd: NavigationEnd) => {
      console.log('navigation end : ', navigationEnd.url);
    })
  );

Upvotes: 1

siddharth shah
siddharth shah

Reputation: 1147

Just call subscribeToEvents() in your constructor. It will definitely solve your problem

Upvotes: 1

jmona789
jmona789

Reputation: 2839

I figured out a solution, I just added a timeout to the navbar's ng-init and then this.router.url gets the correct route.

      setTimeout(() => {
            if (this.router.url === '/projectlist') {
                this.currentPage = "projects";
                this.page = "Project List"
            } else if (this.router.url === '/dashboard') {
                this.currentPage = "dashboard";
                this.page = "Dashboard";
            } else if (this.router.url === '/equipmentlist') {
                this.currentPage = "equipment";
                this.page = "Equipment"
            } else if (this.router.url === '/recipelist') {
                   ... more routes ...
            } else {
                this.page = "Default";
            }
        }, 100);

Upvotes: 2

Related Questions