2017-10-17 100 views
0

我想向角度应用程序添加多语言功能,并且希望在网站加载时设置默认语言。我有两种语言,西班牙语和英语,默认语言是西班牙语。为了实现我有以下路由定义:获取角度为4的参数

const routes: Routes = [ 
    { 
    path: ':lang', component: LanguageComponent, 
    children: [ 
     { path: 'route1', component: Component1 }, 
     { path: 'route2', component: Component2 }, 
     { path: 'route3', component: Component3 }, 
     { path: 'route4', component: Component4 }, 
     { path: '', component: Component1 , pathMatch: 'full' }, 
    ], 
    }, 
    { path: '', redirectTo: 'es', pathMatch: 'full' } 
]; 

首先是,我不知道这是否是路由的考虑我要实现它有两个相同的路由集,怎样才是正确的结构语言,并在运行时使用我开发的翻译服务进行翻译。我的主要问题是,当我尝试检查路线的参数时,我总是不确定。这是我onInit

this.activatedRoute.params.subscribe((params: Params) => { 
    this.currentLanguage = params['lang']; 
}); 

我也曾尝试:

this.activatedRoute.params.subscribe((params) => { 
    this.currentLanguage = params.lang; 
}); 

我认为这个问题是在重定向,但我不知道如何设置“:郎”参数时,我执行该重定向。那有意义吗?

+0

如果你从'ComponentN'调用你应该调用'this.activatedRoute.parent.params',因为这些路由没有参数,但是它们的父类不会... – n00dl3

回答

0

我认为最好的办法,是要创造AppTranslateService将提供语言集LanguageComponent

@Injectable() 
export class AppTranslateService { 
    public lang: string = 'es'; 
} 

@Component({/*...*/}) 
export class LanguageComponent { 
    constructor(appTranslateService: AppTranslateService, activatedRoute: ActivatedRoute) { 
    activatedRoute.params.subscribe((params) => { 
     appTranslateService.lang = params['lang']; 
    }); 
    } 
} 

,只是阅读其他组件appTranslateService.lang变量。

或者,您可以直接在您的组件中使用Angular的Router进样(例如,这样:router.url.split('/')[1](或者在服务中做一次)。

+0

这是我开始实施的一个解决方案,谢谢!然后我意识到我想要访问lang参数的组件与LanguageComponent不在同一级别,因此我一直都是空的。我重构了组件依赖关系树,并可以很好地通过activatedRoute.params.subscribe访问。干杯! –