Dynamically add meta description based on route in Angular

前端 未结 5 1111
自闭症患者
自闭症患者 2020-12-23 10:55

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 th

5条回答
  •  Happy的楠姐
    2020-12-23 11:42

    First create a SEOService or Something like below:

    import {Injectable} from '@angular/core'; 
    import { Meta, Title } from '@angular/platform-browser';
    
    @Injectable()
    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 in your component, 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'
            } 
          },
    

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

提交回复
热议问题