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())
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())
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');
}
}
Can't you just put the dispatch in the constructor of the HomeComponent?
Otherwise you could use a guard for this:
Route:
path: '/home', component: HomeComponent, canActivate: [DispatchGuard]
Guard
@Injectable()
export class DispatchGuard implements CanActivate {
constructor() { }
canActivate(): boolean {
this.store.dispatch(new SampleAction())
return true;
}
}
The other answers here would work however another option is available if you are using the NGXS Router Plugin. You could listen to the stream for router actions e.g. RouterNavigation
, then if the route matches what you are looking for, dispatch the action.
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());
}
});
}