You need to enable JavaScript to run this app. Angular 11中3个subscribe方法已废弃,如何订阅NavigationEnd事件
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11中3个subscribe方法已废弃,如何订阅NavigationEnd事件

RxJS 6.6 未废弃subscribe方法适配方案

你当前代码中使用的subscribe(() => { ... })属于RxJS 6.6中已标记废弃的重载(直接传入单个next回调)。该版本中唯一未废弃的subscribe重载要求传入Observer配置对象,哪怕仅需处理next事件,也要将回调封装到对象的next属性中,不需要的error、complete属性可省略。

修正后可正常运行的代码示例

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {

  subscription: Subscription;

  constructor(private router: Router) {
  }

  ngOnInit() {
    this.subscription = this.router.events
      .pipe(
        filter((e): e is NavigationEnd => e instanceof NavigationEnd)
      )
      // 核心修改点:将回调封装为带next属性的对象
      .subscribe({
        next: () => { window.scrollTo(0, 0) }
      });
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

扩展说明

  • 该写法完全符合未废弃subscribe方法的参数要求,无需调整tslint配置,也不会触发deprecation规则告警
  • 若需处理错误或流完成事件,只需在同一对象中补充对应属性即可,示例:
.subscribe({
  next: () => { window.scrollTo(0, 0) },
  error: (err) => { /* 自定义错误处理逻辑 */ },
  complete: () => { /* 自定义完成处理逻辑 */ }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 18:27:04