In angular 12, when I am trying to navigate to a route along with query parameters, I am able to get the values of those parameters but they are getting cleared from the url.
I am using the below code to navigate:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
query: any;
constructor(private router: Router) { }
ngOnInit(): void {
}
onEnterSearch() {
this.router.navigate(['/portal'], {queryParams: { q: this.query }})
}
}
I am getting the URL params like this in the navigated component:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-portal',
templateUrl: './portal.component.html',
styleUrls: ['./portal.component.scss']
})
export class PortalComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParamMap.subscribe((paramMap: any) => {
console.log(paramMap.get('q')) // successfully getting the value
});
}
}
For a second my url appears like : http://localhost:4200/portal?q=querytext
But then it get cleared to : http://localhost:4200/portal
I want to retain my URL in the browser's address bar. Not sure why it is getting cleared.
NOTE
this.router.navigate(['/portal'], { queryParams: { q: this.query }, queryParamsHandling: 'merge'})
OR
this.router.navigate(['/portal'], { queryParams: { q: this.query }, queryParamsHandling: 'preserve'})
these parameters didn't help.
Update
Saved parameters are also getting lost
Update 2
Here's how I setup my routes
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { PortalComponent } from './components/portal/portal.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'portal',
component: PortalComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }