我会做一些解决方法,例如:
let hasRouterError = false;
@Injectable()
export class MyErrorHandler implements ErrorHandler {
constructor(private inj: Injector) {}
handleError(error: any): void {
console.log('MyErrorHandler: ' + error);
if(hasRouterError) {
let router = this.inj.get(Router);
router.navigated = false;
}
//throw error; // it is necessarily otherwise handleError won't be executed during next error
}
}
export function MyRouterErrorHandler(error: any) {
console.log('RouterErrorHandler: ' + error);
hasRouterError = true;
throw error;
}
我们必须使用自定义RouteReuseStrategy
:
export class PreventErrorRouteReuseStrategy implements RouteReuseStrategy {
shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null { return null; }
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if(hasRouterError) {
hasRouterError = false;
return false;
}
return future.routeConfig === curr.routeConfig;
}
}
它与DefaultRouteReuseStrategy
此代码中唯一的不同
if(hasRouterError) {
hasRouterError = false;
return false;
}
不要忘记将其添加到提供者数组中:
import { RouteReuseStrategy } from '@angular/router';
...
{ provide: RouteReuseStrategy, useClass: PreventErrorRouteReuseStrategy },
您可以在Modified Plunker中尝试