【问题标题】:'filter' does not exist on type 'Observable<Event>'. How can i fix this problem?'filter' 不存在于类型“Observable<Event>”上。我该如何解决这个问题?
【发布时间】:2021-03-31 09:14:31
【问题描述】:

大家早上好。

这是我的问题,我正在尝试将模板集成到我的 Angular 项目中,但部分代码无法正常工作。 filter 函数似乎不再存在于 Observable 库中(从 10 更新到 11 ?)。

我尝试使用管道,但由于我是 Typescript 和 Angular 的新手,我发现很难适应它。

这是我的代码:

import { DOCUMENT, Location } from '@angular/common';
import { Component, ElementRef, Inject, OnInit, Renderer2, ViewChild } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { NavbarComponent } from './commun/navbar/navbar.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  private _router!: Subscription;
  @ViewChild(NavbarComponent) navbar!: NavbarComponent;

  constructor( private renderer: Renderer2, private router: Router, @Inject(DOCUMENT,) private document: any, private element: ElementRef, public location: Location ) {}

  ngOnInit() {
    var navbar = this.router.events.filter((event:any) => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
      if (window.outerWidth > 991) {
        window.document.children[0].scrollTop = 0;
      } else {
        window.document.activeElement!.scrollTop = 0;
      }
      this.navbar.sidebarClose();

      this.renderer.listen('window', 'scroll', (event) => {
        const number = window.scrollY;
        var _location = this.location.path();
        _location = _location.split('/')[2];

        if ( number > 150 || window.pageYOffset > 150 ) {
          navbar.classList.remove('navbar-transparent');
        } else if ( _location !== 'login' && this.location.path() !== 'nucleoicons') {
          navbar.classList.add('navbar-transparent');
        }
      })
    })
  }
}

它应该可以帮助我管理我的导航栏,但是当我运行项目时,我得到了这个错误:

Error: src/app/app.component.ts:19:37 - error TS2339: Property 'filter' does not exist on type 'Observable<Event>'.
    
19     var navbar = this.router.events.filter((event:any) => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {

有人可以帮我理解如何使它工作吗?另外,如果我的代码有任何问题,请纠正我。

感谢您的帮助!

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    很可能你已经从 RxJS v5 升级到了 RxJS v6+。在此迁移期间,应用运算符的方法发生了变化。

    RxJS v5

    import 'rxjs/add/operator/filter';
    
    this.router.events.filter((event:any) => event instanceof NavigationEnd)
    

    RxJS v6+

    import { filter } from 'rxjs/operators';
    
    this.router.events.pipe(
      filter((event:any) => event instanceof NavigationEnd)
    )
    

    请参阅 here 以获取详尽的迁移指南。

    【讨论】:

    • 谢谢先生!如果我有任何困难,我会看到链接并回复您。
    猜你喜欢
    • 2017-01-23
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2020-02-14
    相关资源
    最近更新 更多