Routing encoded url in angular

45 views Asked by At

In my angular project i have a route as a

  path: 'friend/messages/:encryptedKey/:type',
  component: EncryptedRouteComponent,
  canActivate: [AuthGuard],
,
  path: '**',
  component: PageNotFoundComponent,

if i hit url as

baseUrl/friend/messages/NjgzMw==/inbox

i am navigating to PageNotFoundComponent component and there i gets url as only

baseurl/friend/messages/NjgzMw

thats why its not going to EncryptedRouteComponent how to fix this

this is my code snippet of PageNotFoundComponent

in PagenotFoundComponent i want decoded url as

friend/messages/NjgzMw/inbox

so that i will successfully navigate to EncryptedRouteComponent

1

There are 1 answers

0
Naren Murali On

I am unable to replicate the scenario in stackblitz, but you can use encodeURI or decodeURI to pass the keys if you have problems parsing them normally!

You can also use encodeURIComponent and decodeURIComponent for this!

reference answer

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouterModule, provideRouter, Router } from '@angular/router';
import 'zone.js';
import { TestComponent } from './test/test.component';

const routes = [
  {
    path: 'test/:id/qwerty',
    component: TestComponent,
  },
];

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule],
  template: `
    <router-outlet></router-outlet>
  `,
})
export class App {
  name = 'Angular';

  constructor(private router: Router) {}

  ngOnInit() {
    const encoded = encodeURI('NjgzMw==');
    this.router.navigate(['test', encoded, 'qwerty']);
  }
}

bootstrapApplication(App, {
  providers: [provideRouter(routes)],
});

child

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  standalone: true,
})
export class TestComponent implements OnInit {
  value = '';
  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      this.value = decodeURI(params['id']);
    });
  }
}

stackblitz