Angular8 动态设定页面标题title

一般情况下在页面修改标题需要在每个页面组件里引入:

import { Title } from '@angular/platform-browser';


constructor(
    private titleService: Title
) { }

this.titleService.setTitle("title");

    但是,在每个页面都写一次是不是很繁琐呢,也不利于管理标题。可以将设定标题封装成一个services服务,达到统一修改title的目的。

1. 修改页面入口文件index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{title}}</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

2. 配置页面的路由,设置data属性中的title

const routes: Routes = [
  { path: '',   redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component : LoginComponent , data : { title : "登录" }},
  { path: 'index', loadChildren: () => import('./pages/index/index.module').then(m => m.IndexModule), data : { title : "首页" } },
  { path: '**', component: NotFoundComponent , data : { title : "404" }}
];

3.创建一个公共服务CommonService

import { Injectable } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { map, filter } from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor(
    private router: Router,
    private titleService: Title
) {}

  public setTitle() {
    this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
        map(() => this.router)
      )
      .subscribe((event) => {
        const titles = this.getTitle(this.router.routerState, this.router.routerState.root);
        const title = titles[titles.length - 1];
        // console.log(title);
        if (title) {
          this.titleService.setTitle(title);
        }
      });
  }

  public getTitle(state, parent) {
    const data = [];
    if (parent && parent.snapshot.data && parent.snapshot.data.title) {
      data.push(parent.snapshot.data.title);
    }
    if (state && parent) {
      data.push(...this.getTitle(state, state.firstChild(parent)));
    }
    return data;
  }
}

4.在根模块app.component.ts中调用

        引用注入公共服务CommonService,并调用setTitle设置title

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

import { CommonService } from "@services/common.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {

  constructor(
    private common: CommonService
  ) { }

  ngOnInit() {
    //设置页面标题
    this.common.setTitle();
  }
}

5.运行结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Angular 动态路由是指在运行时根据某些条件动态生成路由。这种方式可以让我们根据不同的场景动态地加载不同的组件或模块。 具体实现方法如下: 1. 在路由模块中声明需要动态生成的路由,但是不需要为它们指定具体的组件或模块。 2. 定义一个服务,该服务负责根据条件生成需要的路由。 3. 在组件中注入该服务,并调用服务中的方法生成路由。 4. 将生成的路由添加到路由器中。 下面是一个示例: 路由模块: ```typescript import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, // 动态生成的路由 { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: '**', component: NotFoundComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ``` 动态路由服务: ```typescript import { Injectable } from '@angular/core'; import { Route } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class DynamicRoutesService { constructor() { } generateRoutes(): Route[] { const routes: Route[] = [ { path: 'product', loadChildren: () => import('./product/product.module').then(m => m.ProductModule) } ]; return routes; } } ``` 组件: ```typescript import { Component, OnInit } from '@angular/core'; import { Router, Route } from '@angular/router'; import { DynamicRoutesService } from './dynamic-routes.service'; @Component({ selector: 'app-root', template: ` <h1>Dynamic Routes Demo</h1> <button (click)="generateRoutes()">Generate Routes</button> `, }) export class AppComponent implements OnInit { constructor( private router: Router, private dynamicRoutesService: DynamicRoutesService ) { } ngOnInit() { // 初始化路由 this.router.resetConfig([...this.router.config, ...this.dynamicRoutesService.generateRoutes()]); } generateRoutes() { // 动态生成路由 const newRoutes: Route[] = this.dynamicRoutesService.generateRoutes(); // 将生成的路由添加到路由器中 this.router.resetConfig([...this.router.config, ...newRoutes]); } } ``` 在上面的示例中,我们定义了一个动态路由服务,该服务负责生成 `product` 路由,并将其添加到路由器中。在组件中注入该服务,并在 `ngOnInit` 生命周期钩子中调用服务中的方法生成路由。然后调用 `router.resetConfig()` 方法将生成的路由添加到路由器中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值