Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angular - Is it possible to stop router navigation based on some condition

I'm new to angular, I want stop the routing when user clicks on refresh button or back button based on some condition. I don't know whether this is possible, if anybody knows help me

constructor(private route: Router) {
    this.route.events
        .filter(event => event instanceof NavigationEnd)
        .pairwise().subscribe((event) => {
            if (expression === true){
                // stop routing 
            } else {
                // continue routing
            }      
        });
}

Can it be possible? If yes, how can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I stumbled upon this question quite a bit after the fact, but I hope to help someone else coming here.

The principal candidate for a solution is a route guard.

See here for an explanation: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

The relevant part (copied almost verbatim) is this implementation:

import { Injectable }           from '@angular/core';
import { Observable }           from 'rxjs';
import { CanDeactivate,
         ActivatedRouteSnapshot,
         RouterStateSnapshot }  from '@angular/router';

import { MyComponent} from './my-component/my-component.component';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<MyComponent> {

  canDeactivate(
    component: MyComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    // you can just return true or false synchronously
    if (expression === true) {
      return true;
    }
    // or, you can also handle the guard asynchronously, e.g.
    // asking the user for confirmation.
    return component.dialogService.confirm('Discard changes?');
  }
}

Where MyComponent is your custom component and CanDeactivateGuard is going to be registered in your AppModule in the providers section and, more importantly, in your routing config in the canDeactivate array property:

{
  path: 'somePath',
  component: MyComponent,
  canDeactivate: [CanDeactivateGuard]
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...