简体   繁体   English

如何在服务中使用 Angular 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:在我的 Ionic Angular 应用程序中,我在下面的标记服务中添加了一个单击事件侦听器:

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 :上面的代码在我的home 组件中调用:

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

Currently, "EXECUTED" is being printed, so the method is being ran.当前,正在打印“EXECUTED” ,因此正在运行该方法。

But when buttonClicked() is executed, I want to use the angular router to navigate to the chat component .但是当执行buttonClicked()时,我想使用 angular 路由器导航到聊天组件

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.我在构造函数中将 router 声明为 public,所以我不知道为什么它没有在这个函数中被拾取。

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 ?我应该能够在服务内导航路线,还是应该在Home 组件内完成?

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)
  },
];

Calling this inside a function() { } refers to the function itself.function() { }调用this指的是函数本身。 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']);
}

Did you inject the Router in the service like this?你有没有像这样在服务中注入Router

import { Router } from '@angular/router';
...
constructor(private router: Router)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM