Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular get full url for a route

Tags:

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

like image 375
mac Avatar asked Dec 03 '17 08:12

mac


People also ask

How do I get current URL in app component?

you can subscribe to router. events and filter for NavigationEnd event to get the current active route url.

What is path match full in Angular?

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

What is URL routing in Angular?

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.

What does ActivatedRoute do in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.


2 Answers

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   } } 
like image 175
bazobehram Avatar answered Sep 22 '22 22:09

bazobehram


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
like image 21
Behnam Aminazad Avatar answered Sep 26 '22 22:09

Behnam Aminazad