I have a very simple Angular 4+ application that fetches data from API and displays the data. I believe this should be possible by using just the root component:{path: 'main', component: MainComponent}
and QueryParams like ?id=1
.
I am able to fetch the query param, but for some reason my router repeats the route+params part of the URL after the already existing route+params part. For example my local address malforms from localhost:4200/main?id=1
into localhost:4200/main?id=1/main?id=1
.
The ActivatedRoute does pick the correct query parameter from the URL but I would like to keep the URL as sanitized as possible. How do I prevent this duplication from happening? I have set <base href='/'>
as per routing requirements in my index.html.
Module:
@NgModule({
imports: [
BrowserModule,
RouterModule,
RouterModule.forRoot(
[
{ path: 'main', component: MainComponent},
]),
CommonModule,
HttpModule,
FormsModule,
NgbModule.forRoot()
],
declarations: [MainComponent],
providers: [
{provide: APP_BASE_HREF, useValue: window.document.location.href},
DataService,
WindowService,
HttpUtil
],
bootstrap: [MainComponent]
})
export class MainModule{}
Component:
@Component({
selector: 'main-component',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
constructor(private dataService: DataService,
private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.activatedRoute.queryParams.subscribe((params: Params) => {
if (!(Object.keys(params).length === 0 && params.constructor === Object)) {
console.log(params);
}
});
}
}
This is caused by your APP_BASE_HREF
{provide: APP_BASE_HREF, useValue: window.document.location.href}
You are telling the app to use window.document.location.href main?id=1
as your basehref. Angular then appends its own routes to the end of the basehref. This is why you are getting the duplication
localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE)
Here are the docs on the functionality of APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)