我有这个路由
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,但结果是一样的
发布于 2016-10-12 20:08:17
我想这就是你要找的
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);
}
}https://stackoverflow.com/questions/39997930
复制相似问题