angular - 获取父url参数

标签 angular

我有这个路由

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/

相关文章:

Angular2/4 - 无法读取未定义的属性订阅

javascript - Angular 5 Material snackbar

angular - 在 Angular 7 中,如何从 Observable 中提取结果?

javascript - 在函数外丢失值

angular - 如何强制下载 Angular PWA

Angular 4 mat-form-field with mat-select

dart - 在angular2中访问数据集映射

javascript - 手动关闭 p-calendar 日期选择器

typescript - 使用 Angular 和 TypeScript 在最新的 NativeScript 中使用参数导航

java - 无法通过 spring-boot 应用程序访问 Angular 页面