我检查了很多问题,互联网也没有运气,所以也许有人遇到过类似的问题...
我实现了一个延迟加载的模块:
{
component: LoginPageComponent,
path: '',
pathMatch: 'full'
},
{
canActivate: [AuthGuard],
loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule),
path: 'home'
},
并且在HomeRoutingModule中,我还有另一个
....
children: [
...
{
path: 'items',
canActivate: [SomeGuard,
loadChildren: () => ....
},
然后终于在那个子懒加载模块路由中:
{
path: 'preview/:id',
canActivate: [ItemLoadedGuard],
component: PreviewPageComponent
},
因此,某些条目的URL将是:/home/items/preview/some-random-id
。在该ItemLoaderGuard
中,我实现了对该资源的BE调用,并在出错时导航到404页。
但是当我通过该实现时:/home/items/preview/wrong-id
我将被重定向到/404
页面。
[我想做的是保留网址并打开404页面组件,因此:/home/items/preview/wrong-id
使用NotFoundPageComponent而不是PreviewPageComponent
我已经尝试过导航附加功能,例如:skipLocationChange
和replaceUrl
,但没有效果。
还有其他方法可以解决此问题,而不是在PreviewPageComponent中添加一些无法找到或无法显示的包装器(下面的示例代码)?
<not-found *ngIf="displayNotFound"></not-found>
<div class="content" *ngIf="!displayNotFound">
....
</div>
我还考虑过将URL存储在本地存储中,导航至404,然后替换没有路径的URL,但是也许有人有更好的解决方案?
将您的Preview.guard.ts更改为
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({providedIn: 'root'})
export class PreviewGuard implements CanActivate {
constructor(private router: Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(next.params.id === '123-works'){
console.log('allowed')
return true;
} else {
console.log('not allowed');
setTimeout(() => this.router.navigateByUrl('404', {skipLocationChange: true}));
return true;
}
}
}