Angular 2+ 监听路由动态设置页面meta

angular2+ 里默认切换路由或者切换组件,页面的meta是不会变化的。
如果想针对每个路由设置页面标题,要使用 Meta 服务,我们需要从 @angular/platform-browser 库导入 Meta 类,然后利用 Angular 依赖注入的机制,通过构造注入的方式注入 Meta 服务。其Meta Service 提供了addTag()、addTags()、getTag()、getTags()、updateTag()、removeTag()、removeTagElement()方法。

1. route设置页面

import { Routes } from '@angular/router';

import { HeroesComponent } from './heroes/heroes.component';
import { HomeComponent } from './home/home.component'

export const rootRouterConfig: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent, data: { title: 'Home-Liu', description: 'home页面', keywords: 'Angular, RxJS, TypeScript, home' } },
  { path: 'heroes', component: HeroesComponent, data: { title: 'heros-Liu', description: 'heroes页面', keywords: 'Angular, RxJS, TypeScript, heroes' } }
]

2. app.component.ts页面

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { Component } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Meta } from '@angular/platform-browser';

export class AppComponent {
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private meta: Meta
  ) { }
  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.meta.updateTag({ name: 'description', content: event['description'] });
        this.meta.updateTag({ name: 'keywords', content: event['keywords'] })
      });
  }
}

猜你喜欢

转载自blog.csdn.net/qq_36012563/article/details/86634882
今日推荐