Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel route change in Angular 2?

I would like to cancel the route change when the user click back or forward button in the browser. So far I manage to capture the route change event as in the code below:

constructor(router:Router) {
  router.events
    .subscribe((event:Event) => {
      // some logic.
      // event.preventDefault(); ?
    });
}

I couldn't find any method / member in event to stop the event default. Then I will get this error on console because I have no route config registered as intended, this is because I use location.go() to modify the url.

Error: Uncaught (in promise): Error: Cannot match any routes: 'Some/Url'

Is there any way to cancel the route change so Angular doesn't look at the route config?

like image 730
hendryanw Avatar asked Aug 21 '16 06:08

hendryanw


People also ask

How to set up routing in Angular 2?

Now, the third step for routing to perform in Angular 2 is setting up the router-outlet in app.component.html, which is the route component of my project. Now, on loading of the root component, it will directly go to app.routing.ts file and depending on the URL requested by the user, the component will be loaded..

How to detect the change in url route in angular?

Detect the change in URL route in NavigationStart’s subscribe method. We can add progress spinner or progress bar whenever a route change detected in Angular applications. Now we will go through an example to understand it further. I have created an Angular app which contains three routes. Aboutus,Services and Contactus.

How to show loading indicators in angular router?

Whenever there is a change in angular router, first it will call NavigationStart method as we have subscribed to it. Here we can create a variable which indicates whether we have to show loading indicators such as progress spinner or progress bar. After navigating to the required route, NavigationEnd event will be called.

How to use httpcancelservice in angular?

The HttpCancelService service will use A Subject which acts as an Observer to Observables. Next, to keep an eye on HTTP calls and Router navigation, we will create an Angular Interceptor. This will also import the Service we created in the previous step. Replace below code in managehttp.interceptor.ts file as shown below:


1 Answers

You may use canDeactivate guard when defining route, this will help you writing logic when changing route.

You may simply return true or false, based upon if you want to continue or reject route navigation, you also get reference to your component instance which is active for that route so as to read any property on it.

Signature of the method is like below,

canDeactivate(component: T,
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot) :  
     Observable<boolean>|Promise<boolean>|boolean

You may read more about it here

like image 105
Madhu Ranjan Avatar answered Oct 12 '22 23:10

Madhu Ranjan