You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10 动态路由同组件同路径如何设置动态data内的pageTitle?

Angular 10 动态路由动态设置data属性解决方案

可以实现,无需修改固定的路由path和绑定的组件,共有两种常用方案可选:

原基础路由配置

export const routes: Routes = [ 
{  
    path: 'template/:templateId',
    component: TemplateComponent,
    data: { pageTitle: 'TEMPLATES'}
}]

方案1:使用Resolver守卫动态注入data值(推荐,符合Angular路由设计规范)

Resolver可以在路由激活前执行逻辑,根据路由参数动态生成需要的pageTitle,自动注入到路由的data/resolve属性中。

  1. 首先创建路由解析器:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class TemplateTitleResolver implements Resolve<string> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<string> {
    // 获取路由中的templateId参数
    const templateId = route.paramMap.get('templateId');
    // 返回拼接好的页面标题
    return of(`TEMPLATES-${templateId}`);
  }
}
  1. 修改路由配置,替换静态data为动态resolve:
export const routes: Routes = [ 
  {  
    path: 'template/:templateId',
    component: TemplateComponent,
    resolve: {
      // 这里的key会自动挂载到路由的data属性下
      pageTitle: TemplateTitleResolver
    }
  }
]
  1. 在TemplateComponent中获取动态生成的pageTitle:
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser'; // 如需修改浏览器标签标题可引入该服务

export class TemplateComponent {
  constructor(private route: ActivatedRoute, private titleService: Title) {
    // 路由不复用场景:直接获取快照数据
    const pageTitle = this.route.snapshot.data['pageTitle'];
    this.titleService.setTitle(pageTitle);

    // 路由会复用、参数会在组件存活时变更场景:订阅data变化
    this.route.data.subscribe(data => {
      const pageTitle = data['pageTitle'];
      this.titleService.setTitle(pageTitle);
    })
  }
}

方案2:组件内直接拼接标题(轻量,适合逻辑简单的场景)

不需要新增Resolver,直接在组件中监听路由参数变化,动态生成pageTitle,也可手动赋值到路由data中:

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

export class TemplateComponent {
  pageTitle: string;
  constructor(private route: ActivatedRoute, private titleService: Title) {
    // 监听路由参数变化,适配参数动态变更场景
    this.route.paramMap.subscribe(params => {
      const templateId = params.get('templateId');
      this.pageTitle = `TEMPLATES-${templateId}`;
      // 手动赋值到路由data中
      this.route.snapshot.data['pageTitle'] = this.pageTitle;
      // 设置浏览器标题
      this.titleService.setTitle(this.pageTitle);
    })
  }
}

内容的提问来源于stack exchange,提问作者aman aditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:15:05