如何在 Angular RxJS 中响应式订阅 URL 更改并获取 URL?

问题描述 投票:0回答:2

我有一个带路由的应用程序,它通过点击按钮来改变(见下面的屏幕)。每次更改时,我都试图将 URL 放入文本框中。怎么做? 到目前为止,我已经能够附加到 ActivatedRoute.queryParams ,但它只有在参数发生变化时才会触发,并且没有参数就无法工作。

// could you help to fix this code?  
url$ = this.activatedRoute.queryParams.pipe(
    map(() => {
      console.log("router.url="+this.router.url); // full URL with params
      return this.router.url.split('?')[0] ;
    })
  )

我正在通过按钮点击代码更改页面:

  btnGoProducts(name?: string){
    if (name)
      this.router.navigate(['/products'], {queryParams: {name: name}});
    else
      this.router.navigate(['/products']);
  } 

此屏幕上只有右键有效(因为参数订阅发生变化):

页面代码:app.component.ts 整个测试应用程序:github.com/sam-klok/AngularPlayRoutes

angular rxjs router rxjs-observables
2个回答
0
投票

有两种访问参数的方法。第一个是使用

route.snapshot.paramMap
,第二个是通过
route.paramMap.subscribe
.

用法:

import { ActivatedRoute } from "@angular/router";
constructor(private route: ActivatedRoute) { }

然后您可以访问它供您使用:

this.route.snapshot.paramMap.get("name")

或第二种方式:

this.route.paramMap.subscribe(params => {
  const name = params.get("name")
  });

何时使用

route.snapshot.paramMap

如果您不打算在同一时间更新您的 URL 参数 您正在访问它的组件,那么您可以使用快照。

顾名思义,参数只会被访问一次,当 组件加载。因此,即使您更改,它也不会更新 它的价值来自同一组件。

何时使用

route.paramMap.subscribe

如果你想在你的同一部分更改 URL 参数 网站,您可以使用订阅。这在 Angular 中很容易做到,并且 它仅在您想要更改同一部分中的 URL 时才有效 网站。


0
投票

我不确定我是否理解你,你订阅了 queryParams 所以它会检测它们何时更改,如果你想检测路由更改并将整个 url(带有查询参数)作为 Observable 你可以试试这个网址$:

进口:

import { Router, NavigationEnd } from '@angular/router';
import { map, filter } from 'rxjs/operators';

声明变量 url$:

 url$: Observable<string> = new Observable<string>();

设置url$值:

this.url$ = this.router.events.pipe(
  filter((event: any) => event instanceof NavigationEnd),
  map((event: NavigationEnd) => JSON.stringify(event.url))
);
© www.soinside.com 2019 - 2024. All rights reserved.