首页 文章

类型'Observable<Event>'上不存在Angular 6 router.events.filter 'filter'

提问于
浏览
18

我已经完成了将我的应用程序更新为Angular 6(它是在5.2版本中) .

我有一个错误语法:

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
...
constructor(private router: Router) {}

this.router.events.filter
      (event => event instanceof NavigationEnd).subscribe((res) => 
    {
      // DO something
    });

错误TS2339:类型'Observable'上不存在属性'filter' .

Angular 6中的语法是什么?

谢谢

2 回答

  • 44

    这是使用Angular 6和最新RxJS过滤路由器事件的方法:

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
    
    import { filter } from 'rxjs/operators';
    
    export class MyComponent implements OnInit {
        constructor(private router: Router, private activatedRoute: ActivatedRoute) {}
    
        ngOnInit() {
            this.router.events.pipe(
                filter(event => event instanceof NavigationEnd)
            ).subscribe(() => {
                console.log(this.activatedRoute.root);
            });
        }
    }
    

    使用 pipe 运算符而不是尝试对observable进行链式过滤 .

  • 2

    如果您导入过滤器,我在您的代码中没有看到

    对于Rxjs 6:

    import { filter } from 'rxjs/operators';
    
        .
        .
        .
    
         this.router.events.pipe(
           filter((event:Event) => event instanceof NavigationEnd)
         ).subscribe(res => console.log(res))
    

相关问题