角度路由器:如何替换param?

问题描述 投票:6回答:8

让我们假设我有3个网址:/:projectId/info/:projectId/users/:projectId/users/:userId/profile。所有人都有param projectId。 UI有一个组件可以从一个项目切换到另一个项目。所以我需要:

  1. 获取当前网址
  2. 按名称更改参数(例如projectId)
  3. 导航到新网址

所以我需要像this.router.replaceParam(currentUrl, {projectId: 'project_id_2'})那样将/project_id_1/users/user_id_1/profile变换为/project_id_2/users/user_id_1/profile(以及任何其他带:projectId param的URL)

我认为这是一个简单而常见的问题,但在1小时内没有找到解决方案。建议的here解决方案不起作用,如上一条评论中所述

angular angular2-routing angular-routing
8个回答
3
投票

要从当前网址导航到特定链接,您可以执行以下操作,

 constructor(private route: ActivatedRoute, private router: Router){}
 ngOnInit() {
     this.route.params.subscribe(params => {
         // PARAMS CHANGED ..    

         let id = params['projectid'];    
     });
 }
 navigate(){
     this.router.navigateByUrl(this.router.url.replace(id, newProjectId));
     // replace parameter of navigateByUrl function to your required url
 }

在ngOnInit函数中,我们订阅了params,因此我们可以观察并执行url参数中任何更改的语句。


2
投票

您可以使用HTML或Ts

1>在HTML中

[routerLink]="['../info']"
        Or
[routerLink]="['../users']"
    like this etc....

2>在打字稿中

this.router.navigate(['../users'], { relativeTo: this.activatedRoute });

0
投票

查看您的问题,您想要更改2个参数。

如:

https://angular.io/api/router/Router#navigatebyurl

你可以实现router.navigate([yourprojectId, 'users', youruserId , 'profile'], {relativeTo: route});


0
投票

这会有帮助吗?

export class MyComponent {

  constructor(private router: Router, private route: ActivatedRoute){}

  public navigate(){
    const projectId = getNewProjectId(route.snapshot.params['projectId']);
    this.router.navigate([
      projectId, 
      this.router.url.substring(this.router.url.indexOf('/') + 1, this.router.url.length)
    ]);
  }
}

如果您需要更精细的控制(基本上,您不知道当前URL应该是什么样子),请尝试遍历路由树,处理路由配置路径。您可以在那里找到:projectId配置,并根据您在树中的位置,您可以了解您的router.url结构。

let route = activatedRoute.snapshot;
while (route) {
  if (route.routeConfig && route.routeConfig.path) {
    // Do something with the path
  }
  route = route.parent;
}

希望这有所帮助 :-)


0
投票

这是你可以做到的一种方式。获取网址,获取当前的参数(因为它听起来你不知道它们是什么),如果你有projectid和userid然后你路由到两者。如果网址在'o'结束,那么你在/info路线,如果它在's'结束,那么它是/users路线。

constructor(private activatedRoute: ActivatedRoute) {}

replacePrarm(projectId) {
  // get current url
  const url = this.router.url;

  // get current params
  this.activatedRoute.params.subscribe((params: Params) => {
       if(params['projectId'] && params['userId']) {
          router.navigate(projectId, 'users', params['userId'], 'profile'], {relativeTo: route});
       } else if (url[url.length - 1] === 'o') {
          router.navigate(projectId, 'info'], {relativeTo: route});
       } else if (url[url.length - 1] === 's') {
          router.navigate(projectId, 'users'], {relativeTo: route});
       }
  });
}

这是假设你不知道你在哪条路线上,但在所有现实中你应该知道你是否在用户,信息或个人资料中。否则,您将在三个非常不同的页面上使用一个组件。


0
投票

在相应的组件(即.ts文件)中,您需要添加

import { Subscription } from 'rxjs/Subscription';

Uder进入你的@component使用以下

myVariable: {projectId: string, userId: string};
paramsSubscription: Subscription;


ngOnInit(){
this.myVariable = {
   projectId: this.route.snapshot.params['projectId'],
 // userId: this.route.snapshot.params['userId']
};
this.paramsSubscription = this.route.params
  .subscribe(
    (params: Params) => {
      this.myVariable.projectId = params['projectId'];
    //  this.myVariable.userId = params['userId'];
    }
  );
}

以及你有兴趣改变现有route.let的方法,你想要改变以下方法的路线

changeRoute(): void{
   this.router.navigate(['/curentUrl',this.project_id_2, 'users/user_id_1/profile']);
}

希望这可以帮助你


0
投票

您可以使用:

this.router.navigate(
      [],
      {
        relativeTo: this.activatedRoute,
        queryParams: {projectId: 'project_id_2'},
        queryParamsHandling: "merge", // remove to replace all query params by provided
      });

0
投票

由于我也花了几个小时调查这个问题,我也想分享我的解决方案。

我在应该能够在accountNames之间切换的路由中添加了一个自定义数据项(在您的情况下为projectIds):

const routes: Routes = [
 {
   path: 'expenses/:accountName',
   component: ExpenseListComponent,
   data: { changeAccountUrl: ['expenses', ':accountName'] },
 }
];

这样,任何组件都可以轻松检查activatedRoute的数据是否存在该项目。如果存在,您可以使用它生成路线。

另一个好处是您可以更好地控制生成的路线。

© www.soinside.com 2019 - 2024. All rights reserved.