1

I have a scenario where search can be performed only either of one value (id or age or sex).

If i use below route where only id is passed,

this.router.navigate(['details'],
{
     queryParams: 
     {
         id: this.id,
         age: this.age,
         sex: this.sex,
     }
 })

url will look like http://path/details?id=10&age=&sex=

I want my url to be like

path/details?id=10 on id search

path/details?age=25 on age search

So i refactored my code to,

if(this.id) {
    this.router.navigate(['details'],
    {
         queryParams: 
         {
             id: this.id
         }
     })
}else if(this.age){
    this.router.navigate(['details'],
    {
         queryParams: 
         {
             age: this.age
         }
     })
}else if(this.sex){
    this.router.navigate(['details'],
    {
         queryParams: 
         {
             sex: this.sex
         }
     })
}

Is there better way to refactor the code to avoid if statement

1

1 Answer 1

3

You can simply do this, :

this.router.navigate(['details'],
{
     queryParams: 
     {
         id: this.id || null,
         age: !this.id && this.age || null,
         sex: !this.id && !this.age && this.sex || null
     }
 });

The above will give you the result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.