获取 angular 中的参数 4

Get param in angular 4

我想向 angular 应用程序添加多语言功能,并且我想在网站加载时设置默认语言。我有两种语言,西班牙语和英语,默认语言是西班牙语。为此,我定义了以下路由:

const routes: Routes = [
  {
    path: ':lang', component: LanguageComponent,
    children: [
      { path: 'route1', component: Component1 },
      { path: 'route2', component: Component2 },
      { path: 'route3', component: Component3 },
      { path: 'route4', component: Component4 },
      { path: '', component: Component1 , pathMatch: 'full' },
    ],
  },
  { path: '', redirectTo: 'es', pathMatch: 'full' }
];

首先,考虑到我想要实现的目标是为两种语言设置相同的路由并在运行时使用翻译服务执行翻译,我不确定这是否是正确的路由结构我开发了。我的主要问题是,当我尝试检查路线的参数时,我总是不确定。这是我的 onInit:

this.activatedRoute.params.subscribe((params: Params) => {
  this.currentLanguage = params['lang'];
});

我也试过:

this.activatedRoute.params.subscribe((params) => {
  this.currentLanguage = params.lang;
});

我认为问题出在重定向上,但我不知道在执行该重定向时如何设置“:lang”参数。这有意义吗?

我认为最好的解决方案是创建 AppTranslateService,它将提供 LanguageComponent 中设置的语言:

@Injectable()
export class AppTranslateService {
  public lang: string = 'es';
}

@Component({/*...*/})
export class LanguageComponent {
  constructor(appTranslateService: AppTranslateService, activatedRoute: ActivatedRoute) {
    activatedRoute.params.subscribe((params) => {
      appTranslateService.lang = params['lang'];
    });
  }
}

并只读取其他组件中的 appTranslateService.lang 变量。

或者,您可以直接在组件中从 Angular 的 Router 注入中获取所需的参数,例如这样:router.url.split('/')[1](或在服务中执行一次)。