Krishna
Krishna

Reputation: 9

Angular 12 Routing shows UTF-8 characters like '%2F', '%3F' in the URL and shows can not match any routes. URLSegment error

I have an Angular app which needs to show the homepage after login. When the app logs in correctly, the URL shown in the URL bar contains UTF-8 characters like '!', '%2F', '%3F' which on reload shows the error Error: Cannot match any routes. URL Segment: '!'

app-routing.module.ts

const routes: Routes = [
    {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
    },
    {
        path: 'login',
        component: LoginComponent,
        pathMatch: 'full'
    },
    {
        path: 'screen/:screenName',
        component: ScreenComponent,
        pathMatch: 'full',
        canActivate: [AuthGuard]
    },
    {
        path: 'screen/:screenClassName/:screenId',
        component: ScreenComponent,
        pathMatch: 'full',
        canActivate: [AuthGuard]
    },
    {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuard]
    },
];

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true,
            onSameUrlNavigation: 'reload',
            relativeLinkResolution: 'legacy',
            enableTracing: true
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }

For navigating to the routes, following function is used

Navigation Method

        this.router.navigate(urlTree, navigationExtras).then((state) => {
            if (state) {
                const [path, ...paramsValues] = urlTree;
                const safePath = path ? path.replace('/', '') : path;
                const params = this.routeParams.getParamsFromPath(safePath, paramsValues);

                if (navigationExtras && navigationExtras.queryParams) {
                    this.routeParams.setParams(Object.assign(navigationExtras.queryParams, params));
                }
            }
        });

    setParams(params: object) {
        for (const key in params) {
            if (params.hasOwnProperty(key)) {
                this[key] = params[key];
            }
        }
    }

     getParamsFromPath(path: string, params: any[]): any {
        if (!path) {
            return null;
        }

        const activeRoute = this.router.config.find((route) => {
            const inPathParams = route.path.split('/');

            if (inPathParams[0] === path) {
                return (inPathParams.length - 1) === params.length;
            }

            return false;
        });

        if (!activeRoute) {
            return null;
        }

        const activeRouteParams = activeRoute.path.split('/');

        const routeParamsObj = {};
        activeRouteParams.forEach((paramKey) => {
            if (paramKey.startsWith(':')) {
                const key = paramKey.replace(':', '');
                routeParamsObj[key] = params.shift();
            }
        });

        return routeParamsObj;
    }

Now, when the application moves to new route after login, it shows the following kind of URL in the URL bar in browser

http://localhost:4200/#!#%2Fhome%3Fguid=c217-21f6-189f-8b69-a1a6&screenId=3b3f2275-0ad4-48d6-bd76-8270cb9b9807

With the above URL in browser, when we try and reload the page, it shows the following error and redirects back to the login page

Error: Cannot match any routes. URL Segment: '!'

Angular Version used: 12.2.9

Could this be an issue with Angular 12 or am I doing something really wrong here ?

Upvotes: 0

Views: 1342

Answers (2)

Joël-Etienne
Joël-Etienne

Reputation: 436

I had some problems with the page reload containing special characters I did this for example when I reload a page containing queryParams:

this.router.navigate([], {
  relativeTo: this.activatedRoute,
  queryParamsHandling: 'merge',
});

Hope it can help some

Upvotes: 0

LxstInNxght
LxstInNxght

Reputation: 162

This might help you? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Upvotes: 0

Related Questions