Angular获取路线的完整URL

mac*_*mac 9 angular

想知道是否有办法检索给定路线的完整网址?

在Angular应用程序中,您可以使用router.navigate('...')哪个会立即将浏览器导航到给定路径,但是有没有办法构建URL字符串?

用例就是与OAuth2这样的第三方服务进行通信,我需要提供回调网址,我希望不要用手来构建它,但是调用类似router.urlFor('callback')会产生类似东西的东西"http://localhost:4200/callback"

位置服务prepareExternalUrl但不幸的是它不是需要的

编辑:

目前似乎不可能并且没有简单的开箱即用解决方案,但在查看源代码后找到以下解决方案:

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
Run Code Online (Sandbox Code Playgroud)

createrUrlTree正在routerLink指令下调用

小智 7

你可以试试这个:

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
  }
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike -1

你能做一些列出这个来获取网址列表并发送你想要的网址吗?````

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';


@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit {

  constructor(private router: Router) { }
  urls: string[] = [];

  ngOnInit() {

    this.router.config.forEach(r => {
      console.log(r)
      this.urls.push(this.buildUrl(r.path));
    })
  }

  buildUrl(path: string) {
    return `${environment.basePath}/${path}`
  }

}
Run Code Online (Sandbox Code Playgroud)

````