Angular 6 router.events.filter&#39; filter&#39;在类型&#39; Observable <event>&#39;上不存在

时间:2018-05-15 14:46:18

标签: angular typescript rxjs angular6 rxjs6

我已完成将我的应用程序更新为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:属性&#39;过滤&#39;在类型上不存在   &#39;可观察&#39;

Angular 6中的正确语法是什么?

感谢

3 个答案:

答案 0 :(得分:68)

这是使用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); }); } } 运算符,而不是尝试对可观察对象进行链式过滤。

答案 1 :(得分:2)

如果导入了过滤器,我在代码中看不到

对于Rxjs 6:

import { filter } from 'rxjs/operators';

    .
    .
    .

     this.router.events.pipe(
       filter((event:Event) => event instanceof NavigationEnd)
     ).subscribe(res => console.log(res))

答案 2 :(得分:0)

激活的路由没有给我URL。所以我尝试了这个。 附言:event ['url']代替了event.url

import { filter } from 'rxjs/operators';
import { Router,NavigationEnd } from '@angular/router';

 router.events.pipe(filter(event => event instanceof NavigationEnd))
        .subscribe(event => 
         {
            this.currentRoute = event['url'];          
            console.log(this.currentRoute);
         });