本文介绍了Angular 6 router.events.filter'filter'在类型'Observable< Event>'上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在时出现错误语法:

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

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

what's the right syntax in Angular 6 ?

谢谢

推荐答案

这是如何使用Angular 6+和最新的RxJS过滤路由器事件:

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

使用pipe运算符,而不是尝试对可观察对象进行链式过滤.

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

这篇关于Angular 6 router.events.filter'filter'在类型'Observable< Event>'上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:29