gpt4 book ai didi

javascript - 从 Angular 6 路由器获取语言前缀作为参数

转载 作者:行者123 更新时间:2023-12-04 14:22:39 24 4
gpt4 key购买 nike

我有一个 Angular (6.0.3) 应用程序,我想使用该语言作为所有路由的通用前缀,例如 /en/foo/bar .我的路线定义 src/app/submodule/submodule.routes.ts看起来像这样:

export const submoduleRoutes = [
{ path: ':lingua/foo/bar', component: FooBarComponent },
];

我的根组件 src/app/app.component.ts :
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, Event, NavigationEnd } from '@angular/router';

import { filter } from 'rxjs/operators';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy {
title = 'app';
private sub: any;


constructor(private router: Router, private route: ActivatedRoute) {

this.router.events.pipe(
filter((event:Event) => event instanceof NavigationEnd)
).subscribe(x => console.log(x));
};

ngOnInit() {
this.sub = this.route.params.subscribe(params => {
console.log(params);
});
}

ngOnDestroy() {
this.sub.unsubscribe();
}
}

当我导航到 /xy/foo/bar , FooBarComponent被渲染。但是我无法在根组件中检索语言前缀。 params哈希为空。

控制台输出首先显示 {}对于空参数,然后是 NavigationEnd事件。

相同的代码在 FooBarComponent 中按预期工作.显然,根组件是获取参数的错误位置。

我的目标实际上是获得 lingua所有组件的参数,以便我可以设置正确的语言。我知道我也可以将语言存储在 cookie 或本地存储中,但我需要多语言内容的书签 URL。

如果重要,源代码在 https://github.com/gflohr/Lingua-Poly (提交 12608dc)。有问题的路由在 https://github.com/gflohr/Lingua-Poly/blob/master/src/app/main/main.routes.ts 中定义(最后, :lingua/mytest

最佳答案

你需要让他们成为 App.component 的 child 让它工作。

例如:

const routes = [
{ path: ":lingua", component: AppComponent, loadChildren: 'app/main/main.module#MainModule' },
{ path: "", pathMatch: "full", redirectTo: "/en" }
]

这将从主模块加载所有子路由,但允许 AppComponent访问 lingua范围。

然后您需要删除 :lingua从你的 child 路线的一部分

Here is a StackBlitz example

关于javascript - 从 Angular 6 路由器获取语言前缀作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com