英文:
How to add /en/routerLink to url in angular
问题
他们希望在网址中将页面翻译成英文时包含/en/,我该如何做到这一点?
英文:
I made my page in English with ngx translate core, but when the company translates the page to English, they want /en/ in the url, how do I do that?
答案1
得分: 1
首先,我建议您查看Tour of Heroes。
其次,这是一个实时示例。
无论如何,我使用的方法非常简单(当然,必须根据需要进行调整、改进和更好的处理。这只是为了演示目的)。
我已经定义了组件的路由如下:
{
path: 'site/:lang/foo',
component: TestComponent,
}
然后,我添加了一个通用函数,通过其路由加载组件并传递动态语言:
this._router.navigate([`site/${lang}/foo`]);
最后,在组件中,我只是打印出数据:
@Component({
selector: 'app-test-component',
template: `
<div>Page is in {{lang}}</div>
<div>Full URL: {{url}}</div>
`,
styles: [``],
standalone: true,
})
export class TestComponent implements OnInit {
public lang!: string;
public url!: string;
constructor(private _ar: ActivatedRoute) {}
public ngOnInit(): void {
this.lang = this._ar.snapshot.params?.lang === 'en' ? 'English' : 'Spanish';
this.url = window.location.href;
}
}
窗口中的结果是:
页面语言是英语
完整网址:https://stackblitz-starters-s3fnj9.stackblitz.io/#/site/en/foo
注意网址中的 en
通过单击 "es" 按钮,您将看到组件和网址根据您的请求而更改。
英文:
First, I suggest you to have a look at the Tour of Heroes
Second, this is a live example
Anyway, the approach I used is very simple (and of course must be adapted, improved and better handlded. It's just for a demonstration purpose).
I've defined the route for the component as following:
{
path: 'site/:lang/foo',
component: TestComponent,
},
Then I've added a generic function that loads the component by its route passing a dynamic language:
this._router.navigate([`site/${lang}/foo`]);
Finally, in the component, I just print out the data:
@Component({
selector: 'app-test-component',
template: `
<div>Page is in {{lang}}</div>
<div>Full URL: {{url}}</div>
`,
styles: [``],
standalone: true,
})
export class TestComponent implements OnInit {
public lang!: string;
public url!: string;
constructor(private _ar: ActivatedRoute) {}
public ngOnInit(): void {
this.lang = this._ar.snapshot.params?.lang === 'en' ? 'English' : 'Spanish';
this.url = window.location.href;
}
}
The result in the window is:
> Page is in English
> Full URL: https://stackblitz-starters-s3fnj9.stackblitz.io/#/site/en/foo
Note the en
in the url
By clicking the es
button, you'll see the component and the url changing according to your request.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论