Property 'filter' does not exist on type 'Observable'

后端 未结 7 1473
盖世英雄少女心
盖世英雄少女心 2021-01-31 13:38

Hi I am using Angular 2 final with router 3.0. I want to filter the events that are emitted from this.router.events

What I want to do :



        
7条回答
  •  误落风尘
    2021-01-31 14:10

    There are several possible fixes for this scenario.

    1) Use pipeable operators

    Pipeable operators are meant to be a better approach for pulling in just the operators you need than the "patch" operators found in rxjs/add/operator/*

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

    2) Use 'rxjs/add/operator/filter'

    Change the import statement to import 'rxjs/add/operator/filter'. This will modify Observable.prototype and add filter method to an every instance of the Observable class.

    There are two consequences:

    • it is enough to execute the import statement just once per the application
    • in a shared library/npm package this might bring some confusion to a library consumer (filter() method will magically appear under Observable while using the library)

    3) Leave the operator import but change how it is called

    The statement import 'rxjs/operator/filter' is perfectly valid. It will import just the operator. This approach will not mess with the Observable.prototype. On downside it will make it more difficult to chain several operators.

    import 'rxjs/operator/filter'; // This is valid import statement.
                                   // It will import the operator without 
                                   // modifying Observable prototype
    // ..
    
    // Change how the operator is called
    filter.call(
       this.router.events, 
       (event:Event) => event instanceof NavigationEnd
    ).subscribe(x => console.log(x));
    

    More details: Pipeable Operators

提交回复
热议问题