angularngxsangular-state-managmement

Run a function on matched URL in Angular NGXS


Is there a way to run a function when matched a specific URL. For example: If i matched a URL "/home". Would it possible to run this action

this.store.dispatch(new SampleAction())


Solution

  • 1.- For a single Route:

    You could just execute your function in the onInit()-function of your Component:

    import { Component, OnInit } from '@angular/core';
    
    @Component({
    })
    export class YourComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
    //your code here
      }
    
    }
    

    As soon as your navigating to the route, your function will be executed. Note that your route should be added to your routing-moudle:

    const routes: Routes = [
      {path: 'youRoute', component: YourComponent}
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {
    }
    

    2.- Same Function multiple Routes

    If you want to execute the same code for multiple routes you could listen to route changes. Your router outlet should look like this:

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

    And in your component:

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