Reputation: 524
What I am trying to accomplish is to when I navigate to PageOne from PageTwo it will fire a method addSomthing() {}. But I do not want to fire the method when navigating from PageThree.
is there a way to use NavigationExtras from @angular/router to accomplish this.
.ts
goToPageOne(passed_number: string) {
let navigationExtras: NavigationExtras = {
state: {
severityNumberPass: passed_number
// add something to fire method addSomething
}
};
this.router.navigate(['/PageOne'], navigationExtras);
}
Upvotes: 1
Views: 198
Reputation: 20014
There are a couple of ways to achieve this but with the brief description you provide I would use CanDeactivate
or CanActivate
methods
Both are interface that you implement as a service on angular and set them a router level:
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot
, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}
Implemented like:
@Injectable({
providedIn: 'root',
})
export class SomeServiceGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
//--> someMethod() could be invoked here
console.log('Some validation can go here #canActivate called');
return true;
}
}
In the routes it is configured like
export const ROUTES: Routes = [
{ path: '', component: AppComponent },
{
path: 'other',
component: OtherComponent,
canActivate: [SomeServiceGuard] //<--- here
},
Upvotes: 1