【问题标题】:How to use Angular Router inside a Service to navigate between components?如何在服务中使用 Angular 路由器在组件之间导航?
【发布时间】:2020-07-03 06:51:51
【问题描述】:

在我的 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');
    }
}

上面的代码是在我的home组件中调用的:

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

目前,“EXECUTED”正在打印,所以方法正在运行。

但是当 buttonClicked() 执行时,我想使用角度路由器导航到 聊天组件

我尝试了以下代码:

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

无法读取未定义的属性“导航”

我在构造函数中将router声明为public,所以我不知道为什么它没有在这个函数中被拾取。

如何使用此功能导航到聊天组件

我应该能够在服务中导航路线,还是应该在 Home 组件中完成?

这是我的路线:

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

【问题讨论】:

    标签: angular angular-router


    【解决方案1】:

    你有没有像这样在服务中注入Router

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

    【讨论】:

      【解决方案2】:

      function() { } 内调用this 指的是函数本身。而是在类上声明函数,并在箭头函数中调用它。

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

      【讨论】:

        猜你喜欢
        • 2019-02-02
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 2020-11-04
        • 2017-11-02
        • 2021-09-24
        • 2021-01-04
        • 2019-06-02
        相关资源
        最近更新 更多