Angular 2 Cancelling Route Navigation on UnAuthenticate

前端 未结 3 1978
星月不相逢
星月不相逢 2021-01-16 09:27

I have an app, with 3 links: Home (/), Sign in (/user/sign-in) and User Detail (/user).

When user click Home, my app will be show content public

When user cl

3条回答
  •  抹茶落季
    2021-01-16 10:20

    An unofficial solution that I found to this is to throw a NavigationCancelingError through an observable or a promise. Angular's router will catch this error type, cancel the navigation, and reset the current route. For example, this can be done in a resolve like so:

    import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router';
    import { NavigationCancelingError } from '@angular/router/src/shared';
    import { Observable } from 'rxjs';
    
    export class CancelingResolve implements Resolve {
        constructor(private router: Router) {}
    
        resolve(route: ActivatedRouteSnapshot): Observable {
            this.router.navigate(['new-route']); // Router will navigate here after canceling the activated route.
            return Observable.throw(new NavigationCancelingError());
        }
    }
    

    Note: Works under Angular 2.3.1

提交回复
热议问题