Angular - 在路由器事件中获取组件实例

标签 angular typescript angular-routing

我正在尝试为我的 angular 10 应用程序实现标题服务。我需要订阅路由事件,抓取激活路由的组件,看看它是否实现了title() getter 然后用它来设置页面的标题。听起来很容易...
编码:

    this.router.events
      .pipe(
        filter((event) => event instanceof NavigationEnd),
        map(() => this.rootRoute(this.route)),
        filter((route: ActivatedRoute) => route.outlet === "primary"),
        filter(
          (route: ActivatedRoute) =>
            ComponentWithTitleBase.isPrototypeOf(route.component as any)
        ),
        map((route) => (route.component as unknown) as ComponentWithTitleBase),
        tap(console.dir)
      )
      .subscribe((comp: ComponentWithTitleBase) => {
        this.titleSvc.title = comp.title;
      });
但是comp.title总是未定义的。即使组件确实实现了 get title() setter/getter :
export class AboutComponent extends ComponentWithTitleBase implements OnInit {
  get title(): string {
    return "About the demo";
  }

  ...
}
我看到了 console.dir输出 关于组件 .我在这里缺少什么?

最佳答案

基于@yurzui 的想法,您可以为此使用指令:
激活的component.directive.ts

@Directive({
  selector: 'router-outlet'
})
export class ActivatedComponentsDirective {

  constructor(r: RouterOutlet, titleService: TitleService) {
    r.activateEvents.pipe(
      // takeUntil(r.destroyed),
    ).subscribe(compInstance => compInstance.title && titleService.newTitle(compInstance.title))
  }

  ngOnDestroy () {
    // destroyed.next;
    // destroyed.complete();
  }
}
标题.service.ts
@Injectable({
  providedIn: 'root'
})
export class TitleService {

  private src = new Subject<string>();

  newTitle (t: string) {
    this.src.next(t);
  }

  constructor() { this.initConsumer() }

  private initConsumer () {
    this.src.pipe(
      /* ... */
    ).subscribe(title => {
      console.log('new title', title);
    })
  }
}
ng-run demo .

关于Angular - 在路由器事件中获取组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63122863/

相关文章:

angular - 使用 Angular 进行跨场验证

angular - 我在使用嵌套在 ng-bootstrap 选项卡中的 scss 选择器时遇到问题

javascript - Sweetalert 中的服务无法运行

javascript - 从基类访问和执行子类中的函数

angularjs - 关于使用 angularjs 或 vuejs 进行客户端路由的 SEO 方面

Angular 路由 "opens"新页面在前一个页面之上,并在每个路由操作中保持堆叠

javascript - 从 GoJS 中的 base64 图像字符串获取图像高度和宽度

angular - 类型 'null' 的参数不可分配给参数 Angular

html - 如何在 Angular 中将表(数组)索引添加到组件中

Angular 路由: create different language path route to the same component form navbar component