typescript 在Angular 4中基于活动路由动态设置页面标题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 在Angular 4中基于活动路由动态设置页面标题相关的知识,希望对你有一定的参考价值。

// This can probably be simplified somehow. Not sure why I need to add it in the component to init the service.

import { Component, OnInit } from '@angular/core';
import {TitleService} from "./@core/utils/title.service";

@Component({...})
export class AppComponent implements OnInit {

  constructor(private titleService: TitleService) {...}

  ngOnInit(): void {
    this.titleService.init();
  }
}
import ...

@NgModule({
   ...
   providers: [ TitleService ],
})
export class AppModule { ... }
// If a route is declared with a title attribute, it gets used, otherwise we just try to parse the url fragment
// Here's where the title attribute goes

const routes: Routes = [{
    path: '',
    component: HomeComponent,
    data: {title: "My Home Page"},
  }, {
    path: 'detail/:id',
    component: DetailComponent,
  }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ExampleRoutingModule {
}
// Credits and thanks:
//   https://toddmotto.com/dynamic-page-titles-angular-2-router-events
//   https://stackoverflow.com/questions/34597835/how-to-get-current-route

import { Injectable } from '@angular/core';

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

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

const APP_TITLE = 'NoDice!';
const SEPARATOR = ' > ';

@Injectable()
export class TitleService {
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title,
  ) {}

  init() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => {
        let route = this.activatedRoute;
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .map((data) => {
        if ( data.title ) {
          // If a route has a title set (e.g. data: {title: "Foo"}) then we use it
          return data.title;
        } else {
          // If not, we do a little magic on the url to create an approximation
          return this.router.url.split('/').reduce((acc, frag) => {
            if ( acc && frag ) { acc += SEPARATOR; }
            return acc + TitleService.ucFirst(frag);
          });
        }
      })
      .subscribe((pathString) => this.titleService.setTitle(`${APP_TITLE} ${pathString}`));
  }

  static ucFirst(string) {
    if ( !string ) { return string; }
    return string.charAt(0).toUpperCase() + string.slice(1);
  }
}

以上是关于typescript 在Angular 4中基于活动路由动态设置页面标题的主要内容,如果未能解决你的问题,请参考以下文章

在 Angular 2/4 中使用 typescript 动态创建 HTML 元素数组

基于 npm 和 typescript 构建 Angular 应用程序的指南

在 Angular 4/5 和 TypeScript 中重新加载同一页面

基于ZKWeb + Angular 4.0的开源管理后台Demo

typescript 使用指令将控制集中在角4 #angular

typescript Angular 4基本动画#angular #js