Wondering if there is a way to retrieve full url for a given route?
In Angular app you might use router.navigate('...')
which will immediately navigate your browser to given route, but is there a way just to build URL string?
Use case for this is communication with 3rd party services like OAuth2 where I need to provide callback url, I wish not to build it by hands but call something like router.urlFor('callback')
which will produce something like "http://localhost:4200/callback"
There is Location service which has prepareExternalUrl
but unfortunately it is not what is needed
Edit:
At moment seems that it is not possible and there is no easy out of the box solution, but after looking around at sources find following solution:
const urlTree = router.createUrlTree(['callback'], {
queryParams: { foo: 'bar' },
fragment: 'acme'
});
const path = location.prepareExternalUrl(urlTree.toString());
const url = window.location.origin + path;
console.log(url); // http://localhost:4200/callback?foo=bar#acme
createrUrlTree
is being called underneath routerLink
directive
you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.
pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.
Routes And Paths # Routes are definitions (objects) comprised from at least a path and a component (or a redirectTo path) attributes. The path refers to the part of the URL that determines a unique view that should be displayed, and component refers to the Angular component that needs to be associated with a path.
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.
You could try this :
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'stackoverflow'; constructor(private router: Router) { console.log(this.router['location']._platformLocation.location.origin); // result: http://localhost:4200 } }
You can get baseurl with the following code on javascript
const parsedUrl = new URL(window.location.href);
const baseUrl = parsedUrl.origin;
console.log(baseUrl);
and then concatenate it with for example /callback
to make
http://localhost:4200/callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With