我有这个路由
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,但结果是相同的
最佳答案
我想这就是你要找的
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);
}
}
关于angular - 获取父url参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997930/