我有这个路由
import { ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { ChildComponent } from './app.child-component';
import { Child2Component } from './child2-component';
const appRoutes: Routes = [
{
path: '',
redirectTo: 'AppComponent',
pathMatch: 'full'
},
{
path: ':lang',
children:
[
{
path: '',
component: ChildComponent
},
{
path: 'Child2Component',
component: Child2Component
}
]
}
];
export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
我想从我的函数中获取lang参数:
translateThis(lang: any) {
// this line works fine
this.translate.use(lang);
// this doesn't
this.sub = this.route.parent.queryParams.subscribe(
(param: any) => {
let lang = param['lang'];
console.log(param);
console.log(userId);
});
}
但是当我取消注释this.sub代码(整整6行)时它会停止工作。没有它,它可以正常工作
translateThis(lang: any) {
this.translate.use(lang);
}
我怎样才能获得lang值?我也尝试了params
而不是queryParams,但结果是相同的
答案 0 :(得分:0)
我想这就是你要找的东西
translateThis() {
// Subscribe to router params observable
this.sub= this.route.parent.params.subscribe(
param => {
let lang = param['lang'];
console.log(lang);
// Call method or something
this.translate.use(lang);
});
}
以下是我认为您需要的完整示例。请注意,路线参数的订阅应该手动取消订阅
export class ChildComponent implements OnInit, OnDestroy {
private sub;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Subscribe to router params observable
this.sub= this.route.parent.params.subscribe(
param => {
let lang = param['lang'];
console.log(lang);
// Call method or something
this.translateThis(lang);
});
}
ngOnDestroy() {
// Unsubscribe from router params observable
this.sub.unsubscribe();
}
translateThis(lang: any) {
// Do your thing here
// this.translate.use(lang);
}
}