fun*_*kid 2 javascript routes typescript angular
当我的后端向我发送404错误(URL 有效,只是因为找不到资源,例如http://localhost:4200/post/title-not-exist)时,我希望 Angular 重定向到我的NotFoundComponent,而不更改浏览器中的 URL。
代码如下(简化):
\n\nconstructor(private router: Router, private location: Location) {}\n\nhandleError(err: HttpErrorResponse) {\n switch (err.status) {\n case 404:\n url = this.router.routerState.snapshot.url;\n // \'**\' is set in the app-routing.module.ts\n // { path: \'**\', component: NotFoundComponent }\n this.router.navigate([\'**\'], { replaceUrl: false });\n // weird here too\n // without the setTimeout(), replaceState will not work\n setTimeout(() => {\n this.location.replaceState(url);\n });\n break;\n\n default:\n break;\n }\n return throwError(err);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在,我可以重定向到NotFoundComponent并且 URL 没有更改,问题是:
/post/title-exist\xe2\x86\x92 /post/not-exist\xe2\x86\x92 /post/not-exist/post/title-exist\xe2\x86\x92 /post/not-existsetTimeout(),location.replaceState()将不起作用,浏览器中的 URL/**不会更改为之前快照的 URL。更新
\n\n用于skipLocationChange保留原始 URL,replaceUrl不再需要。
\n参考这里。
原来的
\n\n关键点是将replaceUrlinthis.router.navigate从更改false为true,如下所示:
this.router.navigate([\'**\'], { replaceUrl: true });\nRun Code Online (Sandbox Code Playgroud)\n\n背后逻辑:
\n\nreplaceUrl是 时false,您正在将新历史记录推送到浏览器历史记录堆栈中。于是历史栈就变成了这样:/post/title-exist\xe2\x86\x92 /post/title-not-exist\xe2\x86\x92/**
并在 的帮助下replaceState(),将/**历史记录更改为/post/title-not-exist,这使得历史记录最终变为:
/post/title-exist\xe2\x86\x92 /post/title-not-exist\xe2\x86\x92/**/post/title-not-exist
replaceUrl是 时true,你直接修改当前的历史记录堆栈,这使得你的浏览器历史记录变成这样:/post/title-exist\xe2\x86\x92/post/title-not-exist/**
然后,在 的帮助下replaceState(),历史变成:
/post/title-exist\xe2\x86\x92/post/title-not-exist/**/post/title-not-exist