首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取父url参数

问获取父url参数
EN

Stack Overflow用户
提问于 2016-10-12 19:52:27
回答 1查看 1.1K关注 0票数 1

我有这个路由

代码语言:javascript
复制
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参数,如下所示:

代码语言:javascript
复制
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行),它就停止工作了。没有这个,它就可以正常工作了。

代码语言:javascript
复制
translateThis(lang: any) {
    this.translate.use(lang);
}

如何获得该lang值?我也尝试了params,而不是queryParams,但结果是一样的

EN

回答 1

Stack Overflow用户

发布于 2016-10-12 20:08:17

我想这就是你要找的

代码语言:javascript
复制
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);
  });
}

这里有一个完整的例子,我相信你需要什么。请注意,应手动取消对路由参数的订阅

代码语言:javascript
复制
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);
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39997930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档