Tea*_*s20 2 rxjs typescript angular angular11
我想在 Angular 11 中订阅 NavigationEnd 事件,同时使用 rxjs 中的过滤器。
\nsubscribe((event: NavigationEnd) ...导致以下问题的部分
目前的解决方案:
\n\n\nTS2769:没有与此调用匹配的重载。\xc2\xa0\xc2\xa0Overload 1 of 5, '(observer?: NextObserver | ErrorObserver | CompletionObserver | undefined): Subscription',给出以下错误。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 类型“(event: NavigationEnd) => void”的参数不可分配给类型“NextObserver |”的参数 错误观察者 | 完成观察者 | 不明确的'。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 类型“(event: NavigationEnd) => void”中缺少属性“complete”,但类型“CompletionObserver”中需要该属性。\xc2\xa0\xc2\xa0Overload 2 of 5, '(下一个?: ((值: 事件) => void) | 未定义,错误?: ((错误: 任何) => void) | 未定义,完整?: ( () => void) | undefined): 订阅',出现以下错误。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0类型“(event: NavigationEnd) => void”的参数不可分配给类型“(value: Event) => void”的参数。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0参数'event'和'value'的类型不兼容。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type“Event”不可分配给类型“NavigationEnd”。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 类型“RouterEvent”中缺少属性“urlAfterRedirects”但在“NavigationEnd”类型中需要。
\n
请参阅下面的构造函数代码以及提到的代码片段:
\nexport class NavigationService implements OnDestroy {\n private readonly routeChange: Subscription | undefined;\n private previousUrl: string | undefined;\n private ignoredRoutes = ['/signup', '/login', '/reset'];\n\n constructor(private router: Router) {\n this.routeChange = router.events\n .pipe(filter(event => event instanceof NavigationEnd))\n .subscribe((event: NavigationEnd) => {\n if (!this.ignoredRoutes.includes(event.url)) {\n this.previousUrl = event.url;\n }\n });\n }\n\n ngOnDestroy(): void {\n if (this.routeChange) {\n this.routeChange.unsubscribe();\n }\n }\n\n public routeToPreviousContent(): void {\n //route home if undefined\n const targetUrl = this.previousUrl ? this.previousUrl : '';\n this.router.navigate([targetUrl]).then();\n }\n}\nRun Code Online (Sandbox Code Playgroud)\nTS2769 在这种情况下有效吗?我假设带有 的 rxjs 过滤器管道event instanceof NavigationEnd根本无法识别?!
Ste*_*ado 13
传递给过滤器的函数不是类型保护,但您可以像这样指示类型:
constructor(private router: Router) {
this.routeChange = router.events
.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd)
)
.subscribe(event => {
// "event" here is now of type "NavigationEnd"
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4436 次 |
| 最近记录: |