我如何将 redirectTo 与包含参数的 url 一起使用?

How do i use redirectTo with an url containing a parameter?

当路径为 '' 时,我希望将用户重定向到相对路径 ':lang/home'。但是,当我导航到 localhost:4200/.

时,HomeComponent 不会加载

这是代码片段:

const routes: Routes = [
  { path: '', redirectTo: ':lang/home', pathMatch: 'full' },

这仅在我将 :lang 替换为 en/home 等硬编码语言代码时有效。 我试过 localhost:4200/:lang/home/:lang/home 但这也不起作用。 两者都给出浏览器错误:

ERROR Error: Uncaught (in promise): Error: Cannot redirect to '/:lang/home'. Cannot find ':lang'.
Error: Cannot redirect to '/:lang/home'. Cannot find ':lang'.
    at ApplyRedirects.findPosParam

我该如何解决这个问题?谢谢

制作路线守卫,

@Injectable()
export class HomePageRedirect implements CanActivate {
    canActivate() {
        //Your redirect logic
    
    if (this.user && this.user.lang) {
     this.router.navigate([this.user.lang,"home"]);
    }
    return true;
}
//Constructor 
constructor(private router: Router) { }
}

在你的路线中,

  { path: '' pathMatch: 'full', component: HomeComponent, canActivate:[HomePageRedirect] },