0

i'm currently working on an angular app which is opened on a particular url:

localhost:3000/?param1=abc,def&param2=abcdefghi 

Now i want to implement angular routing . So i have 2 routes : 1. mainComponent 2.dataComponent

in my index.html ,have set the as :

<base href="/">

After configuring the app to use routing , my app opens with only localhost:3000 , and even after adding the param1,param2 to the url , it is getting redirected to localhost:3000

How can i solve this ? as the parameters are passed only on opening the link and it is dynamic

app.module.ts:

const appRoutes: Routes = [
  { path: 'mainComponent', component: MainComponent },
  { path: 'dataComponent',      component: DataComponent },
  {path : '' , component:MainComponent}
];

app.component.html:

<nav>
    <a routerLink="/mainComponent" routerLinkActive="active">Main</a>
    <a routerLink="/dataComponent" routerLinkActive="active">Data</a>
</nav>
<router-outlet></router-outlet>

1 Answer 1

2

You need to change your routes as following

const appRoutes: Routes = [
 {path : '' ,redirectTo: 'mainComponent', pathMatch: 'full'},
 { path: 'mainComponent', component: MainComponent },
 { path: 'dataComponent',      component: DataComponent },
];

And better way to provide links

<nav>
    <a [routerLink]="['/mainComponent']" routerLinkActive="active">Main</a>
    <a [routerLink]="['/dataComponent']" [queryParams]="{ param: "paramValue" } routerLinkActive="active">Data</a>
</nav>

To receive parameters you need to do following in your component constructor

constructor(private activatedRoute: ActivatedRoute){
    this.type = activatedRoute.snapshot.params['type'];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the reply . i made the changes you mentioned , but after clicking on the Data , the url which had the parameters also vanished . is there any way the parameters are not removed on changing the route ?
Not by default - you will need to write a method to handle that using the router.navigate() method and attaching your current parameters. See this tutorial: angular.io/tutorial/toh-pt5
@CruelEngine to pass query parameters you need to do this <a [routerLink]="['/dataComponent']" [queryParams]="{ param: "paramValue" } routerLinkActive="active">Data</a> see my updated code

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.