我已经完成将我的应用程序更新到 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
});
error TS2339: Property 'filter' does not exist on type 'Observable'.
Angular 6 中正确的语法是什么?
谢谢
最佳答案
这是使用 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);
});
}
}
使用 pipe
运算符而不是尝试对可观察对象进行链式过滤。
关于Angular 6 router.events.filter 'filter' 在类型 'Observable<Event>' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353164/