如何根据路由更改父组件上的标头

Dan*_*eve 0 html javascript angular-routing angular

使用 Angular 7.x,我想根据子路由以及它们是否被激活来更改我的父标头组件。所以就我而言

AppComponent   
     Feature Module <= detect changes here    
          Child Components of feature module
Run Code Online (Sandbox Code Playgroud)

所以我的路由非常简单,app-routing.module只包含使用loadChildren加载功能模块,这里没什么花哨的。

然后这个功能模块包含子组件的路由。有一个父组件,我们称其ParentComponent为包含路由器出口的组件。我还想根据孩子的情况相应地更改一些标题。

所以我有两个子组件:create和 ' :id'(详细信息页面)。当我触发这些路由时,我需要父组件相应地更改其文本内容。因此,例如,当触发创建页面时,我想添加标题:“创建新项目”,对于 :id 页面,我想显示“详细信息页面”。

现在,我发现我需要订阅路由器事件或激活的路由(或快照)。我在这里不知所措,所以我真的不知道在这里做什么。

我的父组件现在看起来像这样:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
})
export class ParentComponent implements OnInit {
  title = 'Parent Title';
  // Check if it is possible to change the title according to the route
  subtitle = 'Parent subtitle';

  constructor(private readonly router: Router, private readonly route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.url.subscribe(data => {
      if (this.route.snapshot.firstChild) {
        console.log('yes', this.route.snapshot.firstChild);
        // Change header with a if/else or switch case here
      } else {
        // Display standard text 
        console.log('no');
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

这是 console.logs 的输出,请注意,在我的实际应用程序中,父级名为“timesheets”。

在此输入图像描述

是否有其他解决方案?也许是一项服务,但所有信息基本上都已经在路线中了,所以我试图弄清楚这是否是解决我的问题的方法。

Har*_*maz 5

您可以监听NavigationEnd事件,ParentComponent或者(我认为)更好的是您可以使用标题服务。


解决方案一:

ParentComponent

import {NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';
...



constructor(private router: Router, private readonly route: ActivatedRoute) {
    this.subscribeRouterEvents();

}

subscribeRouterEvents = () => {
    this.router.events.pipe(
      filter(e => e instanceof NavigationEnd)
    ).subscribe(() => {

       this.title = this.route.snapshot.data['title'];
       // Assuming your route is like:
       // {path: 'path', component: MyComponent, data: { title: 'Page Title'}}
    });
Run Code Online (Sandbox Code Playgroud)

解决方案2:

使用TitleService。创建一个保存页面标题的服务,订阅标题ParentComponent并将新标题发送到服务ChildComponent

产权服务

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

  private defaultTitle = 'Page Title';
  private titleSubject: BehaviorSubject<string> = new BehaviorSubject(this.defaultTitle);
  public title: Observable<string>;

  constructor(private titleService: Title) {
    this.title = this.titleSubject.asObservable();
  }

  public setTitle(title: string) {
    this.titleSubject.next(title);
  }
}
Run Code Online (Sandbox Code Playgroud)

父组件

pageTitle = 'Page Title';
constructor(private titleService: TitleService) {}

ngOnInit(){
  this.titleService.title.subscribe(value => this.pageTitle = value);
}
Run Code Online (Sandbox Code Playgroud)

子组件

pageTitle = 'Child Component Title';
constructor(private titleService: TitleService) {}

ngOnInit(){
  this.titleService.setTitle(this.pageTitle);
}
Run Code Online (Sandbox Code Playgroud)