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
相关产品推荐
相关产品推荐

