Match a route with "localhost:4200/test-(dynamic parameter)" at Angular 7

Asked

Viewed 150 times

3

Summary of the problem: It is one of those friendly URL’s that will be sent and within the parentheses will come next to the airport of the city, I need the route to be activated when it comes with these parameters.

Ex: /voos-sao-paulo(gru) based on this route URL voos- (which is the work of the function matcher that is in stackblitz) I need to make a request by passing sao-paulo and gru (which will be extracted from the url) which is the airport of Womens for the API. The parameters of the city and the acronym of the airport will be dynamic and will have others as date, other airports and etc.

The function matcher stackblitz works because all coming Urls will necessarily start with voos-.

The problem is that with what comes inside the ( ) does not match the route and Angular throws an error and I can not catch what comes in the URL, if you come a route without the ( ) with only gru the route enters the function matcher and works as expected.

Stackblitz simulating the problem

https://stackblitz.com/edit/angular-nadrke?file=src%2Fapp%2Fapp.component.html

  • https://stackblitz.com/edit/angular-a8bdrn?file=src/app/hello.component.ts I set up your stackblitz just type /anything at the end of the url that should work

  • You want to extract the value of parentheses ?

  • @Eduardovargas did not serve

  • @Victorhenrique edited the post and I believe I have put a better explanation

  • Try to do with httpInterceptors if or with this dynamic parameter and call a service with parameters like in my stackblitz

  • Can not use Interceptor pq will not ta at the angle yet

Show 1 more comment

1 answer

1


In his AppComponent just in the ngOnInit check the window.location.pathname which is what the angular router will scan to find the routes.

Remember to insert into the main component of your application.

if(window.location.pathname.includes('(') || window.location.pathname.includes(')')) {
   window.location.pathname = window.location.pathname.replace(/\(/g, '%28').replace(/\)/g, '%29');
}

Example: https://stackblitz.com/edit/angular-p13och?file=src/app/app.component.ts

Another alternative is you put in your index.html a script tag right after closing the tag app-root the content below.

<script> window.history.pushState("", "", window.location.pathname.replace(/\(/g, '%28').replace(/\)/g, '%29') + window.location.search); </script>

Example: https://stackblitz.com/edit/angular-pyka24?file=src/index.html

NOTE: I don’t think these solutions are elegant, but I believe it’s the only way to solve your problem.

  • it worked thanks I used the last solution!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.