When I navigate to a page with query parameters in my Angular application, the parameters end up disappearing.
For example, if I go here:
http://example.com:8080/TestComponent?OtherName=foo
If reroutes me to here:
http://example.com:8080/TestComponent
Thus, since the query parameters get erased, my subscription to ActivatedRoute
returns nothing. This is my routing:
import { Routes } from '@angular/router';
import { TestComponent, PageNotFoundComponent } from './exports/components';
export const ROUTES: Routes = [
{
path: 'TestComponent',
component: TestComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
Subscription (route
is an instance of ActivatedRoute
):
this.route.queryParams.subscribe((params: Params) => {
if (params && Object.keys(params).length > 0) {
const OTHER_NAME = params['OtherName'];
}
});
Even if I remove the wildcard path, it still removes the parameters from the URL; therefore, it never goes inside the the above if
statement. How can I prevent the query parameter from disappearing?
This is can be an exact solution for this, but I found an approximate solution.
url = localhost:4200/#/test?id=1234
use auth-guard-service and CanActivate your page.
1.Angular routing
{ path: 'test', component: TestComponent, canActivate: [AuthGuardService]}
2.AuthGuardService
@Injectable({ providedIn: 'root' })
export class AuthGuardService implements CanActivate {
constructor(private app: ApplicationService) {
// window.location.href => gives you exact url (localhost:4200/#/test?id=1234).
// you can parse url like this.
id = getUrlParameterByName('id', window.location.href);
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const curPage = route.url[0].path;
if('test' === curPage) { return true; }
else {
// your decision...
}
}
getUrlParameterByName(name: string, url?: any) {
if (!url) { url = window.location.href; }
name = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
const results = regex.exec(url);
if (!results) { return null; }
if (!results[2]) { return ''; }
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With