在角度2中,如何使每页的规范标签动态化

Ang*_*arM 5 javascript google-webmaster-tools canonical-link angular

在角度2中,如何使每页的规范标签动态化.

这是我的索引页面标记:

  <link rel="canonical" href="https://mywebsite.co.uk" />
Run Code Online (Sandbox Code Playgroud)

如何使其动态化,例如,如果在博客页面上它应该在运行时看起来像这样:

  <link rel="canonical" href="https://mywebsite.co.uk/blog" />
Run Code Online (Sandbox Code Playgroud)

我正在使用角度版本4,webpack和带有ng2元数据的打字稿来更改我所有网址的标题,说明和关键字.

我只需要为seo google bot更改规范标签.

des*_*iny 0

我实现了一个在页面组件的 ngOnInit 函数中调用的服务:

import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable()
export class LinkService {

  private link: HTMLLinkElement;

  constructor(@Inject(DOCUMENT) private doc) { }

  createLinkForCanonicalURL() {
    if (this.link === undefined) {
      this.link = this.doc.createElement('link');
      this.link.setAttribute('rel', 'canonical');
      this.doc.head.appendChild(this.link);
    }
    this.link.setAttribute('href', this.doc.URL.split('?')[0]);
  }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:https ://www.concretepage.com/angular/angular-title-service-and-canonical-url