Angular 7 路由器:如果路由数据中未提供,则使用默认标题
Angular 7 Router: use default title if one not provided in route data
在几篇文章和 SO 帖子之后,我已将我的应用程序配置为显示页面标题作为 "title":
的路由器数据参数
const routes: Routes = [
{
path: '',
component: BadgesComponent,
data: {
title: 'Design System - Badges'
}
}
];
但是,我的一些路由可能没有添加这个参数;在这种情况下,我想显示一个包罗万象的标题,例如 "Design System"。我拼凑的代码(如下)查找数据元素,但我不知道如果数据元素丢失,如何向简单字符串添加回退。
值得注意的是 index.html
有一个 title
我想要的默认值,它在我添加此代码之前显示。添加代码后,它会被覆盖 — http://localhost:8082/#/badges
显示为页面标题(例如)
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { map, filter, mergeMap } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title
) {}
ngOnInit() {
this.router.events
.pipe(
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.titleService.setTitle(event['title']));
}
}
为什么不在您已有的订阅代码中执行此操作?
.subscribe(event => this.titleService.setTitle(event['title'] || 'Design System'));
在几篇文章和 SO 帖子之后,我已将我的应用程序配置为显示页面标题作为 "title":
的路由器数据参数const routes: Routes = [
{
path: '',
component: BadgesComponent,
data: {
title: 'Design System - Badges'
}
}
];
但是,我的一些路由可能没有添加这个参数;在这种情况下,我想显示一个包罗万象的标题,例如 "Design System"。我拼凑的代码(如下)查找数据元素,但我不知道如果数据元素丢失,如何向简单字符串添加回退。
值得注意的是 index.html
有一个 title
我想要的默认值,它在我添加此代码之前显示。添加代码后,它会被覆盖 — http://localhost:8082/#/badges
显示为页面标题(例如)
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { map, filter, mergeMap } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title
) {}
ngOnInit() {
this.router.events
.pipe(
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.titleService.setTitle(event['title']));
}
}
为什么不在您已有的订阅代码中执行此操作?
.subscribe(event => this.titleService.setTitle(event['title'] || 'Design System'));