我有一个像/orders/first
这样的路线的简单解析器:
resolve(): Promise<Order> {
return this.orderService.get()
.then((response) => response.order)
.catch(error => Promise.reject(error));
}
我还有一个错误处理程序,可以重定向到错误页面:
this.router.navigate(['/error'], { skipLocationChange: true });
我希望网址为/orders/first
,因此如果用户刷新,他可能会查看该网页。这也使后退按钮返回到不正确的页面(上一页上一页)
问题是解析器在路由激活之前运行,因此URL不会更改。
有办法做到这一点吗?
编辑: 找到了这个解决方法:
NavigationStart
并将路由保存到变量this.location.go(nextRoute.url);
skipLocationChange
设置为true 答案 0 :(得分:0)
我已经这样做了:
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any {
return this.clientService.get(route.params.id)
.catch( err => {
const path = this.location.path();
this.router.navigate(["/" + err.status], { skipLocationChange: true })
.then( () => {
this.location.replaceState(path);
});
return Observable.empty();
})
}
答案 1 :(得分:0)
import { Injectable } from '@angular/core';
import { Router, NavigationError, NavigationExtras } from '@angular/router';
import { Location } from '@angular/common';
@Injectable()
export class RouterService {
private errorRoot: string;
constructor(
private router: Router,
private location: Location
) { }
setRouteErrorHandler(errorRoot: string = '/error'): void {
let errorRoute = null;
this.errorRoot = errorRoot;
this.router.errorHandler = (error): void => {
this.router.navigateByUrl(errorRoot, { skipLocationChange: true })
.then(() => this.location.go(errorRoute.url));
};
this.router.events
.filter(next => next instanceof NavigationError)
.subscribe((next) => errorRoute = next);
}
}
从AppModule构造函数或APP_INITIALIZER调用routerService.setRouteErrorHandler()