2017-10-17 110 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訪問。乾杯! –