Angular 6 router.events.filter 'filter' does not exist on type 'Observable<Event>'

AngularTypescriptRxjsAngular6Rxjs6

Angular Problem Overview


I have finished to update my App to Angular 6 (it was in 5.2 version).

I got an error syntax in :

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
    });

> error TS2339: Property 'filter' does not exist on type > 'Observable'.

what's the right syntax in Angular 6 ?

thanks

Angular Solutions


Solution 1 - Angular

This is how to filter router events with Angular 6+ and latest 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);
        });
    }
}

Uses the pipe operator instead of attempting to chain filter on the observable.

Solution 2 - Angular

I don't see in your code if you imported filter

for Rxjs 6:

import { filter } from 'rxjs/operators';
    
    .
    .
    .

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

Solution 3 - Angular

Activated Route wasnt giving me the url. So I tried this. P.S: event['url'] worked instead of 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);
         });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnouar MokhtariView Question on Stackoverflow
Solution 1 - AngularLansana CamaraView Answer on Stackoverflow
Solution 2 - AngularPatricio VargasView Answer on Stackoverflow
Solution 3 - AngularRincy PhilipView Answer on Stackoverflow