我用Angular 5建立了一个小册子类型的网站.到目前为止,我已经设置了路由,页面标题会根据激活的路由动态更改.我使用这个博客上的说明:https://toddmotto.com/dynamic-page-titles-angular-2-router-events

我目前正在应用程序中存储我的路由和标题.单元ts本身:

imports: [
    BrowserModule,
    RouterModule.forRoot([
      { 
        path: '', 
        component: HomeComponent,
        data: {
          title: 'Home'
        }
      },
      { 
        path: 'about', 
        component: AboutComponent,
        data: {
          title: 'About'
        } 
      },
      { 
        path: 'products-and-services', 
        component: ProductsServicesComponent,
        data: {
          title: 'Products & Services'
        }  
      },
      { 
        path: 'world-class-laundry', 
        component: LaundryComponent,
        data: {
          title: 'World Class Laundry'
        }  
      },
      { 
        path: 'contact', 
        component: ContactComponent,
        data: {
          title: 'Contact'
        }  
      },
      { 
        path: '**', 
        component: NotFoundComponent,
        data: {
          title: 'Page Not Found'
        }  
      }
    ])
  ],

我也希望将我的元描述存储在那里,如果将它们添加到data:以下就足够简单了.

我用下面的代码获取标题数据,这在上面的博客链接中有所说明:

ngOnInit() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => {
        this.titleService.setTitle(event['title']);
      });
  }

所以我的问题是,有没有办法用同样的方法动态设置元描述?如果有一种结合页面标题和元描述功能的方法,那将是理想的.

我的Angular 训练非常有限,所以这可能是个问题.我更像是一个设计师/css/html类型的人.

推荐答案

首先创建一个SEOService或类似的东西:

import {Injectable} from '@angular/core'; 
import { Meta, Title } from '@angular/platform-browser';

@Injectable({
  provideIn: 'root' // Add this to ensure your SEO service will be app-wide available
})
export class SEOService {
  constructor(private title: Title, private meta: Meta) { }


  updateTitle(title: string) {
    this.title.setTitle(title);
  }

  updateOgUrl(url: string) {
    this.meta.updateTag({ name: 'og:url', content: url })
  }

  updateDescription(desc: string) {
    this.meta.updateTag({ name: 'description', content: desc })
  }
}

After injecting the SEOService在你的组件中(最好是app.component.ts),在OnInit方法中设置元标记和标题

ngOnInit() {
    this.router.events.pipe(
       filter((event) => event instanceof NavigationEnd),
       map(() => this.activatedRoute),
       map((route) => {
         while (route.firstChild) route = route.firstChild;
         return route;
       }),
       filter((route) => route.outlet === 'primary'),
       mergeMap((route) => route.data)
      )
      .subscribe((event) => {
        this._seoService.updateTitle(event['title']);
        this._seoService.updateOgUrl(event['ogUrl']);
        //Updating Description tag dynamically with title
        this._seoService.updateDescription(event['title'] + event['description'])
      }); 
    }

然后像这样配置你的路由

      { 
        path: 'about', 
        component: AboutComponent,
        data: {
          title: 'About',
          description:'Description Meta Tag Content',
          ogUrl: 'your og url'
        } 
      },

这是一种处理元标记的清晰方法.你可以更容易地更新facebook和twitter特定的标签.

Typescript相关问答推荐

动态判断TypScript对象是否具有不带自定义类型保护的键

TypeScript将键传递给新对象错误

动态调用类型化函数

使某些(嵌套)属性成为可选属性

如何使用泛型自动推断TS中的类型

在函数中打字推断记录的关键字

从子类构造函数推断父类泛型类型

对未到达受保护路由的路由环境做出react

Select 下拉菜单的占位符不起作用

部分更新类型的类型相等

如何在方法中正确地传递来自TypeScrip对象的字段子集?

通过泛型函数本身推断受约束的泛型参数的类型脚本问题

刷新时保持当前名称的Angular

对象类型的TypeScrip隐式索引签名

如何扩展RxJS?

使用&reaction测试库&如何使用提供程序包装我的所有测试组件

有没有什么方法可以使用ProvideState()提供多个削减器作为根减减器

打字:注解`是字符串`而不是`布尔`?

导航链接不触发自定义挂钩

基于可选参数的动态类型泛型类型