Dynamically add meta description based on route in Angular

前端 未结 5 1107
自闭症患者
自闭症患者 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条回答
  •  春和景丽
    2020-12-23 11:24

    Angular 6+ and RxJS 6+ solution for dynamically set title on route change

    If/when you upgrade to Angular 6 this is the solution there.

    This service will:

    • Update meta title on route change.
    • Option to override title for any reasons you want that.

    Create/change your SEO/meta service to the following.

    import { Injectable } from '@angular/core';
    import { Title, Meta } from '@angular/platform-browser';
    import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
    import { filter, map, mergeMap } from 'rxjs/operators';
    
    @Injectable({
        providedIn: 'root'
    })
    export class MetaService {
        constructor(
            private titleService: Title,
            private meta: Meta,
            private router: Router,
            private activatedRoute: ActivatedRoute
        ) { }
    
        updateMetaInfo(content, author, category) {
            this.meta.updateTag({ name: 'description', content: content });
            this.meta.updateTag({ name: 'author', content: author });
            this.meta.updateTag({ name: 'keywords', content: category });
        }
    
        updateTitle(title?: string) {
            if (!title) {
                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.titleService.setTitle(event['title'] + ' | Site name');
                        });
            } else {
                this.titleService.setTitle(title + ' | Site name');
            }
        }
    }
    

    Import your service and call it in the contructor.

    app.component.ts

    constructor(private meta: MetaService) {
        this.meta.updateTitle();
    }
    

    And this still requires to format routes like this.

    Route file.ts

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

    Hope this will help for you and other people looking to update the title/meta dynamically in Angular 6.

提交回复
热议问题