Search code examples
angularangular-router

How to use Angular Router inside a Service to navigate between components?


In my Ionic Angular app, I am adding a click event listener in my marker service below:

makeCapitalMarkers(map: L.map): void {
    map.on('popupopen', function () {
          if (document.querySelector('.norwayLink')) {
            const link = document.querySelector('.norwayLink')
            link.addEventListener('click', buttonClicked)
          }
        });

    function buttonClicked() {
        console.log('EXECUTED');
    }
}

The above code is called in my home component:

ngAfterViewInit(): void {
    this.markerService.makeCapitalMarkers(this.map);
}

Currently, "EXECUTED" is being printed, so the method is being ran.

But when buttonClicked() is executed, I want to use the angular router to navigate to the chat component.

I tried the below code:

function buttonClicked() {
    this.router.navigate(['/chat'])
}

Cannot read property 'navigate' of undefined

I declared router in the constructor as public, so I don't know why it's not being picked up in this function.

How can I navigate to the Chat Component using this function?

Should I be able to navigate routes within the service, or should this be done inside the Home Component?

Here are my routes:

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)},
  {
    path: 'chat',
    loadChildren: () => import('./chat/chat.module').then( m => m.ChatPageModule)
  },
];

Solution

  • Calling this inside a function() { } refers to the function itself. Instead declare the function on the class, and call it inside arrow functions.

    makeCapitalMarkers(map: L.map): void {
      map.on('popupopen', () => {
        if (!eventHandlerAssigned && document.querySelector('.norwayLink')) {
          const link = document.querySelector('.norwayLink')
          link.addEventListener('click', () => {
            this.buttonClicked();
          });
          eventHandlerAssigned = true
        }
      });    
    }
    
    buttonClicked() {
      this.router.navigate(['/chat']);
    }