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

Angular 17升级后报错:TypeError: this.router.events.filter is not a function

解决Angular 17中this.router.events.filter is not a function错误

这个错误源于Angular 17配套的RxJS版本不再支持Observable直接链式调用操作符(如filter、map),所有操作符必须通过.pipe()方法包裹,且需单独导入对应的RxJS操作符。

修复步骤

1. 导入所需的RxJS操作符

在app.component.ts顶部添加以下导入语句:

import { filter, map, mergeMap } from 'rxjs/operators';

2. 修改路由事件处理代码

将ngOnInit中原有的链式操作符调用,全部迁移到.pipe()方法内:

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.updateDescription(event['description'], event['keywords'], event['title']);
});

修改后的关键代码片段

// 顶部新增导入
import { filter, map, mergeMap } from 'rxjs/operators';

// ...其他代码保持不变

ngOnInit() {
  this.seoService.createLinkForCanonicalURL();
  this.router.events.subscribe((evt) => {
    this.loaderSVC.startLoading();      
    if (!(evt instanceof NavigationEnd)) {
      return;
    }
    setTimeout(() => {
      this.loaderSVC.stopLoading();        
    });
    if (isPlatformBrowser(this.platformId)) {
      window.scrollTo(0, 0);

      const userAgent = window.navigator.userAgent;
      sessionStorage.setItem('userAgent', userAgent);
      sessionStorage.setItem('ipAddress', '0.0.0.0');
    }
  });

  // 修改后的路由事件处理逻辑
  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.updateDescription(event['description'], event['keywords'], event['title']);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:54:51