angular - 在 Angular NGXS 中对匹配的 URL 运行函数

标签 angular ngxs angular-state-managmement

有没有办法在匹配特定 URL 时运行函数。 例如: 如果我匹配一个 URL“/home”。是否可以运行此操作

this.store.dispatch(new SampleAction())

最佳答案

1.- 对于单个路线:

您可以在组件的 onInit() 函数中执行您的函数:

import { Component, OnInit } from '@angular/core';

@Component({
})
export class YourComponent implements OnInit {

  constructor() { }

  ngOnInit() {
//your code here
  }

}

一旦您导航到路线,您的函数就会被执行。 请注意,您的路由应添加到您的路由模块中:

const routes: Routes = [
  {path: 'youRoute', component: YourComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

2.-相同功能多条路线

如果您想对多个路由执行相同的代码,您可以监听路由更改。您的路由器 socket 应如下所示:

<router-outlet (activate)="routeChange()"></router-outlet>

在你的组件中:

  constructor(public route: Router) {}    

  myRoutes: string[] = ['/tools', '/home'];

  routeChange() {
    if (this.myRoutes.some(e => e === this.route.url)) {
      console.log('execute');
    } else {
      console.log('dont execute');
    }
  }

关于angular - 在 Angular NGXS 中对匹配的 URL 运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58645412/

相关文章:

angular - NGXS 全局状态的切片在每次导航时发出

angular - 如何在 amcharts 4 中为 LineSeries 添加 click\hit 事件?

javascript - 我如何使这个 angular2 服务稍微同步?

javascript - 如何使用 ngFor 循环复选框,以便它在 angular2 中拥有自己的索引?

angular - 如何取消 ngxs 调度操作

NGXS updateItem 状态操作符

angular - 从 DOM 元素获取 Angular 组件类

angular - NGXS:测试调度 Action 不适用于 ofActionDispatched

angular - 特定实体的大量 Action /效果