【问题标题】:Run a function on matched URL in Angular NGXS在 Angular NGXS 中对匹配的 URL 运行函数
【发布时间】:2020-02-26 22:26:49
【问题描述】:

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

this.store.dispatch(new SampleAction())

【问题讨论】:

  • 当您的 url 匹配时,假设您的“HomeComponent”已加载。只需在 HomeComponent 的 ngOnInit() 上运行它
  • @MoxxiManagarm。这就是我所做的。但是,如果您有许多要匹配的网址怎么办。你会在每个组件的每个 ngOnInit() 上运行它吗?有没有办法只用一个文件来做到这一点?
  • 那么订阅router.events有什么问题,过滤一些事件NavigationEndNavigationStart(我不知道你需要什么),然后过滤需要的url和switchMapstore.dispatch?

标签: angular ngxs angular-state-managmement


【解决方案1】:

这里的其他答案也可以,但是如果您使用的是 NGXS Router Plugin,则可以使用另一个选项。您可以收听路由器操作的流,例如RouterNavigation,然后如果路由匹配您要查找的内容,则调度该操作。

constructor(private actions$: Actions, private store: Store) {

// Listen to the NGXS action stream for when the router navigation changes
this.actions$
    .pipe(ofActionDispatched(RouterNavigation))
    .subscribe(({routerState}: RouterNavigation) => {

      // If routerState matches your conditions then dispatch the action
        if (routerState == ) { 
          this.store.dispatch(new SampleAction());
        }
     });
}

【讨论】:

  • 我会把它放在一个单独的文件中吗?它将如何运行?我需要加入提供者吗?
  • 根据您希望它的工作方式,您可以将其挂接到您的主 app.component 或在应用程序启动时通过 APP_INITIALIZER 加载它
  • 是的,我希望它在应用程序启动时加载。你能编辑你的代码吗?谢谢
  • 在启动时,您需要将其作为提供程序加载到您的主 App.Module - 请参阅示例 here
  • 谢谢 我尝试提供它,但它仍然无法正常工作。当我尝试 console.log 时它没有出现在控制台中
【解决方案2】:

1.- 对于单一路线:

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

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.- 同一功能多条路线

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

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

【讨论】:

    【解决方案3】:

    不能直接把dispatch放到HomeComponent的构造函数中吗?

    否则你可以为此使用警卫:

    路线:

      path: '/home', component: HomeComponent, canActivate: [DispatchGuard]
    

    守卫

    @Injectable()
    export class DispatchGuard implements CanActivate {
    
      constructor() { }
    
      canActivate(): boolean {
        this.store.dispatch(new SampleAction())
        return true;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2012-03-05
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多