角度更改时检测动态页面标题

问题描述 投票:0回答:2

我有一个角度6应用程序,我想在每次路线更改时都存储页面标题,

import { Router, NavigationEnd, NavigationStart, RoutesRecognized } from '@angular/router';

export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
          this.router.events.subscribe(event => {

      if (event instanceof NavigationStart) {
        // console.log('Starting Navigation');
      }

      if (event instanceof NavigationEnd) {
        console.log('Ending Navigation ', document.title);
      }
  });
    }

问题是,每当我要访问当前页面的标题时,它都会显示以前的标题集,而不显示从组件级别动态设置的新标题

任何建议如何解决此问题?

javascript html angular angular6
2个回答
0
投票

您可以在Title中使用@angular/platform-browser类,

进口声明

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

将其注入到构造函数中

constructor(private title:Title){ }

您的router事件订阅将看起来像

this.router.events.subscribe(event => {

      if (event instanceof NavigationStart) {
        // console.log('Starting Navigation');
      }

      if (event instanceof NavigationEnd) {
        alert(this.title.getTitle())
      }
  });

0
投票

我认为您尝试在按组件级别重置文档标题之前访问它。

[当您导航到路由时,路由器会发出一个事件,此后组件将被初始化,如果我对您的理解正确,则标题将在此处重置。

例如,您可以在路线中提供标题数据:

const routes: Routes = [
    {
        path: 'my/route',
        component: MyComponent,
        data: {
           documentTitle: 'YOUR TITLE'
        }
    }
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class MyRouterModule { }
© www.soinside.com 2019 - 2024. All rights reserved.