首页 > 解决方案 > RouterService 中的 this.route 没有正确的 url

问题描述

我试图在我的中编写一个函数RouterService来添加查询参数。这是我的路由器服务

export class RouterService {
  constructor(
    private router : Router,
    private route: ActivatedRoute
  ) { }
  addQueryParams(params : {}){
    debugger;
    console.log(this.route.toString());
    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: params,
      queryParamsHandling: 'merge',
      skipLocationChange: true
    });
  }
}

在此处添加是我正在使用此功能的组件。

navegateRole(){
  this.routerService.addQueryParams({id : "2"});
}

现在,在我的 RouterService 中 this.route 没有给我当前的 active http://localhost:4200/core/enterpriseprofile。它给出了这个Route(url:'', path:'')空对象。

标签: angular

解决方案


this.route在您的代码中代表ActivatedRoute。要从中获取 url,您可以使用urlActivatedRoute 的属性。

由于url属性是可观察的,您需要对其执行一些操作以将其作为字符串获取,例如:

const url: Observable<string> = this.route.url.pipe(map(segments => segments.join('/')));

现在,您可以url像下面这样订阅以获取相对 url:

this.url.subscribe(value=>{
  console.log(value);
});

推荐阅读