Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

angular2 routing - Angular router: how to replace param?

Let's suppose I've got 3 urls: /:projectId/info, /:projectId/users, /:projectId/users/:userId/profile. All of them have param projectId. UI has a component to switch from one project to another. So I need:

  1. Get current URL
  2. Change param by name (e.g. projectId)
  3. Navigate to new url

So I need something like this.router.replaceParam(currentUrl, {projectId: 'project_id_2'}) which will transform /project_id_1/users/user_id_1/profile into /project_id_2/users/user_id_1/profile (and any other URL with :projectId param)

I thought it's a simple and common problem but didn't find a solution in 1 hour. Suggested here solution doesn't work as noted in the last comment

question from:https://stackoverflow.com/questions/50784299/angular-router-how-to-replace-param

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To navigate to particular link from current url, you can do something like this,

 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
 }

On ngOnInit function, we have subscribed to params so we can observe and executes our statements on any change in url parameter.

Edit

Case: where ids can be same

constructor(private route: ActivatedRoute, private router: Router){}
     projectId:string;
     userId: string;
     ngOnInit() {
         this.route.params.subscribe(params => {
             this.projectId = params['projectid']; 
             this.userId = params['userId'];
         });
     }
     navigate(){
         // for /project/:projectId/users/:userId/profile
         this.router.navigate(['/project', this.projectId, '/users', 
         this.userId, '/profile']);
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...