【问题标题】:Angular 4 - Router redirectTo using variable segmentAngular 4 - 使用可变段的路由器重定向
【发布时间】:2017-09-17 18:14:48
【问题描述】:

在下面的路由中,我在尝试获取 http://localhost:4200/ 时收到以下错误

错误错误:未捕获(承诺):错误:无法重定向到“/:userCountry/:userLanguage/home”。找不到“:userCountry”。 错误:无法重定向到“/:userCountry/:userLanguage/home”。找不到“:userCountry”。 在 ApplyRedirects.webpackJsonp.../../../router/@angular/router.es5.js.ApplyRedirects.findPosParam (router.es5.js:1784)

所有其他路由路径都在工作,只有 redirectTo 似乎没有替换变量 userCountry(以及 userLanguage)的值。

任何帮助将不胜感激。

const appRoutes: Routes = [
   { path: '', redirectTo: '/:userCountry/:userLanguage/home', pathMatch: 'full' },
   { path: ':userCountry/:userLanguage/home', component: HomeComponent },
   { path: ':userCountry/:userLanguage/about', loadChildren: './about/about.module#AboutModule' },
   { path: ':userCountry/:userLanguage/terms', loadChildren: './terms/terms.module#TermsModule' },
   { path: ':userCountry/:userLanguage/privacy', loadChildren: './privacy/privacy.module#PrivacyModule' },
   { path: '**', component: PageNotFoundComponent }
];

当错误出现时,我的变量已经有值了。

这是我的 console.log() 的摘录

[AppRoutingModule.constructor]this.userLanguage=fr
    [AppRoutingModule.constructor]this.userCountry=ca  
    ...  
    ERROR Error: Uncaught (in promise): Error: Cannot redirect to '/:userCountry/:userLanguage/home'. Cannot find ':userCountry'

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    userCountryuserLanguage'' 路由中时,您需要将默认值传递给路由匹配。你可以这样做

    const appRoutes: Routes = [
       { path: '', redirectTo: '/germany/ge/home', pathMatch: 'full' },
       { path: ':userCountry/:userLanguage/home', component: HomeComponent }
       ...
    }
    

    【讨论】:

    • 我正在使用 geoip 服务来分配 userCountry 变量('us' 代表美国,'ca' 代表加拿大等等......),我无法对 userCountry 值进行硬编码,因为我的应用根据用户所在的国家/地区显示不同的内容。 userLanguage 也是如此,我不想通过硬编码每个将访问我网站主页的用户的国家/语言来向法语用户显示英语内容,反之亦然,我必须为我的主页动态分配这些值。
    • 所以在这种情况下,您需要首先为'' 加载另一个组件,从中获取适当的值,然后将用户重定向到HomeComponent
    • 嗨,谢谢它解决了我的问题。但是,我不明白为什么我必须使用另一个组件才能在本教程中直接在 redirectTo vsavkin.com/angular-router-understanding-redirects-2826177761fc 中使用变量时进行重定向
    • 因为您必须检测国家/语言。对于'',您直接重定向另一个希望此变量匹配的路由。在该示例中,我没有看到任何具有给定值的重定向
    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 2018-02-14
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2018-12-27
    • 2014-05-09
    相关资源
    最近更新 更多