如何在Angular中将/en/routerLink添加到URL中。

huangapple go评论132阅读模式
英文:

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: &#39;site/:lang/foo&#39;,
    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: &#39;app-test-component&#39;,
  template: `
  &lt;div&gt;Page is in {{lang}}&lt;/div&gt;
  &lt;div&gt;Full URL: {{url}}&lt;/div&gt;
  `,
  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 === &#39;en&#39; ? &#39;English&#39; : &#39;Spanish&#39;;
    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.

huangapple
  • 本文由 发表于 2023年7月10日 16:48:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定