Search code examples
angularurl-routingangular-routingpayment

How to redirect to some component in Angular when the url has multiple variables concatenated with "&"?


From the backend I get the following URL

http://localhost:4200/paypal/?paymentId=PAYID-L7LA6CT5K826252R&token=EC-1R8557872G&PayerID=8ANSA9QW

My target is it to redirect to the home component when this link occurs.

At the moment I am trying to do this with the angular routing module like this:

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'PayPal/:paymentId&:token&:PayerID', component: HomeComponent}
];

How do I have to structure the route for redirecting to the component?


Solution

  • no need to add these query parameters in the route path. you just need to have paypal. And in navigation just navigate by query parameters like this

    Routes

    const routes: Routes = [
      { path: 'home', component: HomeComponent},
      { path: 'paypal', component: HomeComponent}
    ];
    

    Navigation

    import { ActivatedRoute, Router } from '@angular/router';
    
    export class AppComponent  {
      constructor(
         private router: Router,
         private activeRoute: ActivatedRoute
      ) { 
         this.router.navigate(['paypal'], { queryParams: {
           paymentId: 'PAYID-L7LA6CT5K826252R',
           token: 'EC-1R8557872G',
           PayerID: '8ANSA9QW'
         }});
      }
    
    }
    

    Also, you can get these query parameters from the activated route like this

    import { ActivatedRoute, Router } from '@angular/router';
    
    export class AppComponent  {
    
      constructor(
         private router: Router,
         private activeRoute: ActivatedRoute
      ) { 
       // get the params only one time
       console.log(activeRoute.snapshot.queryParams, 'paypal query params');
    
       // or you can subscribe the query param changes
       
       activeRoute.queryParams.subscribe(params => {
             console.log(params, 'paypal query params from the subscription');
       })
      }
    
      
    }