9

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?

o.o
  • 3,563
  • 9
  • 42
  • 71
  • How do you perform the navigation? – ConnorsFan May 29 '18 at 21:13
  • I just type in `http://example.com:8080/TestComponent?OtherName=foo` into the address bar. Then the `Routes` array takes over and sends me to the `TestComponent` html. – o.o May 29 '18 at 21:15
  • 2
    The problem is discussed in [this question](https://stackoverflow.com/q/39898656/1009922). There are solutions when navigating with `routerlink` or with `Router.navigate` but not for the initial URL or when typing the URL in the address bar (as far as I know). There is a [feature request](https://github.com/angular/angular/issues/12664) to allow a global setting to keep the query parameters. – ConnorsFan May 29 '18 at 21:24
  • Aww, thanks for the information. :( – o.o May 30 '18 at 00:54
  • 4
    How is this not a bigger issue?? This seems like an issue that would be fairly common...I'm experiencing something very similar. For me, I have a query before a hash, like so: example.com/?data=123#/home. When I go to this route, the query gets removed. Very frustrating that I can't find a solution for this. I need the query to track a Google Analytics campaign. – awebdev Mar 08 '19 at 21:33

1 Answers1

1

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, ' '));
}
Mesut KAYA
  • 35
  • 6
  • You have example with url = localhost:4200/#/test?id=1234. What if the url is localhost:4200/?id=1234#/test/. How would you proceed – JayC Sep 15 '20 at 17:01
  • i showed here to how to capture url before disappearing, after that you can customize url parsing algorithm for your case. – Mesut KAYA Sep 16 '20 at 06:03