在 Angular 中根据路由动态添加元描述 [英] Dynamically add meta description based on route in Angular

查看:25
本文介绍了在 Angular 中根据路由动态添加元描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular 5 构建一个小型宣传册类型的网站.到目前为止,我已经设置好了路线,并且页面标题会根据激活的路线动态变化.我使用此博客上的说明进行了这项工作:https://toddmotto.com/dynamic-page-titles-angular-2-router-events

I'm using Angular 5 to build a small brochure type website. Thus far, I have my routes set up, and the page title changes dynamically based on the activated route. I got this working using the instructions on this blog: https://toddmotto.com/dynamic-page-titles-angular-2-router-events

我目前将我的路线和标题存储在 app.module.ts 中:

I'm currently storing my routes and titles in app.module.ts as such:

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: 下添加元描述很容易的话,我也想在那里存储我的元描述.

I'd like to store my meta descriptions there as well, if adding them under data: would be easy enough.

我正在使用以下代码提取标题数据,上面的博客链接中对此进行了说明:

I'm pulling in that title data with the following code, which is noted in the blog link above:

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']);
      });
  }

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

So my question is, is there a way to dynamically set the meta description using the same method? If there is a way to combine the page title and meta description function, that would be ideal.

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

I have very limited Angular training, so this might be a nooby question. I'm more of a designer/css/html kind of guy.

推荐答案

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

First create a SEOService or Something like below:

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 })
  }
}

在你的组件(最好是app.component.ts)中注入SEOService后,在OnInit方法中设置元标签和标题

After injecting the SEOService in your component (app.component.ts preferably), set meta tags and title in OnInit method

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'])
      }); 
    }

然后像这样配置你的路线

Then configure your routes like

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

恕我直言,这是一种处理元标记的清晰方法.您可以更轻松地更新 facebook 和 twitter 特定标签.

IMHO this is a clear way of dealing with meta tags. You can update facebook and twitter specific tags easier.

这篇关于在 Angular 中根据路由动态添加元描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆