Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...