【问题标题】:Angular get full url for a routeAngular获取路线的完整网址
【发布时间】:2018-05-16 22:38:37
【问题描述】:

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

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

用例是与 OAuth2 等 3rd 方服务进行通信,我需要提供回调 url,我不希望手动构建它,而是调用类似 router.urlFor('callback') 的东西,这将产生类似 "http://localhost:4200/callback" 的东西

Location 服务有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

createrUrlTreerouterLink 指令下被调用

【问题讨论】:

  • 你试过this吗?
  • @NishadAhsan ActivatedRoute - 包含有关与在插座中加载的组件关联的路线的信息。换句话说,ActivatedRoute 可用于获取有关当前路线的信息,而不是用于生成 url
  • 你喜欢任何答案吗?你会选择一个并将其标记为正确的吗?谢谢!

标签: angular


【解决方案1】:

你可以试试这个:

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
  }
}

【讨论】:

    【解决方案2】:

    您可以在javascript上使用以下代码获取baseurl

    const parsedUrl = new URL(window.location.href);
    const baseUrl = parsedUrl.origin;
    console.log(baseUrl);
    

    然后将其与例如/callback 连接以制作

    http://localhost:4200/callback
    

    【讨论】:

    • 不是很“Angularish”——不推荐这个。
    【解决方案3】:

    您通常在某处配置基本 URL,例如在 yaml 文件中。通过这种方式,您可以配置所有不同的阶段(组件测试、集成测试、附加测试、生产)。在运行时,您将读取配置并使用某种实用程序方法或只是字符串连接来生成您的 taget URL。

    我不会解析 location.href 属性,因为您经常使用负载均衡器、反向代理,因此您不知道要添加到基本 URL 中的确切内容。不过,对于简单的应用,这可能就足够了。

    这里是一个例子:

    您的本地网址:http://localhost:8080/myapp/somefunction 您的制作网址:https://www.somecompany.com/itdepartment/myapp/somefunction

    【讨论】:

      【解决方案4】:

      我认为您在处理 oauth2 时犯了错误。 对于 oauth2 1-前端请求 api 登录,然后 api 将其重定向到外部 oauth2 服务器。 2-然后在登录 oauth2 服务器后将您重定向到 api 回调(它在 oauth2 服务器中指定为 returnUrl)。 3- api 服务器将浏览器重定向到前端应用程序。 所以当前端调用 api 服务器登录时只需设置查询字符串 returnUrl( 的值是当前页面路由,所以它是 location.href) 在 url 并将其发送到 api 然后 api 将保存它并在 api 回调中 api 将客户端重定向到以前保存的 Url。

      【讨论】:

        【解决方案5】:

        您也可以获取完整的路由 URL 和分段。使用以下代码:

            import { Component, OnInit } from '@angular/core';
            import { Router, ActivatedRoute } from '@angular/router';
            
            @Component({
              selector: 'app-hero',
              templateUrl: './hero.component.html',
              styleUrls: ['./hero.component.css']
            })
            export class HeroComponent implements OnInit {
            
              constructor(private router: Router,  private activeRoute: ActivatedRoute) { 
                this.activeRoute.queryParams.subscribe((qp) => {
                  console.log('Get Router URL in segment:', this.activeRoute.snapshot);
                  console.log('Get Full Router URL:', this.router.url);
                });
              }
            
              ngOnInit(): void {
              }    
            }
        
        

        欲了解更多信息check out this link

        【讨论】:

          【解决方案6】:

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

          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}`
            }
          
          }
          

          ```

          【讨论】:

            猜你喜欢
            • 2018-06-23
            • 1970-01-01
            • 2018-04-19
            • 1970-01-01
            • 2014-08-23
            • 1970-01-01
            • 2017-11-28
            • 1970-01-01
            • 2018-09-13
            相关资源
            最近更新 更多