我的路由模塊中有這條路線:
{ path: 'signup', component: SignupComponent },
但是不應該在沒有片段(#first-step, #second-step)的情況下訪問此路由,因此我在我的應用程式中添加了一些重定向邏輯:
this.route.fragment.subscribe((fragment: string | null) => {
if (fragment && ['first-step', 'second-step'].includes(fragment)) {
// Fragments are correct, further logic with displaying step components
} else {
this.router.navigate(['signup'], {fragment: 'first-step', replaceUrl: true});
}
})
我使用navigate片段是因為片段是 url 的客戶端部分,它只能在客戶端上更改,但是瀏覽器歷史記錄存在問題,使用這種方法它會推送 poth 頁面 -signup和signup#first-step. skipLocationChange在這里無濟于事,因為它不會更改網址。我可以簡單地在主頁上的注冊按鈕中定義片段,但是如果用戶直接從書簽或地址欄打開注冊頁面怎么辦?我想在不向signup歷史記錄中添加頁面的情況下進行漂亮的重定向,怎么做?有什么我不正確理解的嗎?
uj5u.com熱心網友回復:
您可以將邏輯移動到 a Guard,以便在導航完成之前得到處理。
@Injectable({ providedIn: 'root' })
export class SignupGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot): boolean | UrlTree {
const {fragment} = route;
// has required fragment proceed with navigation
if (fragment && ['first-step', 'second-step'].includes(fragment)){
return true;
}
//no fragment present, return UrlTree to 'signup#first-step' for redirection
return this.router.createUrlTree(['signup'], { fragment: 'first-step' });
}
}
然后在 Route 中使用守衛:
{
path: 'signup',
component: SignupComponent,
canActivate: [SignupGuard],
runGuardsAndResolvers: 'always',
},
我添加了 ,runGuardsAndResolvers因此在嘗試導航到signuponsignup#first-step或時,守衛也會得到處理signup#second-step。如果在您的應用程式中無法做到這一點,您可以將其洗掉。
干杯
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523603.html
上一篇:如果型別存在,彈性搜索必須匹配
