4

如何在 Angular 5 中获取当前请求的 url?

我尝试了一些在网上找到的解决方案,但似乎没有任何效果。- $window - 在 WindowRef 示例中包装原生窗口

我整个上午都在寻找这个,但对 Angular 来说有点陌生,并且在针对不同版本 Angular 的在线不同示例中迷失了方向。

更新:我正在使用 TypeScript

谢谢

4

4 回答 4

4

如果你想要角度解决方案,你可以使用它。

import { Router } from '@angular/router';

constructor(private router:Router) {}

someMethod(){
  console.log(this.router.url)
}

否则你可以使用标准的窗口解决方案

window.location.href 返回当前页面的 href (URL)。

于 2017-12-04T13:35:52.847 回答
0

要在浏览器地址栏中获取当前 URL,您可以使用 window.location.href。您不需要 Angular 包装器来获取当前 URL。

于 2017-12-04T12:12:32.353 回答
0
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

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

    constructor(private location: Location) {}

    public back(): void {
      this.location.back()
    }

}
于 2019-03-19T07:31:31.470 回答
0

如果你想window.location.href在你的组件中使用 TypeScript,你需要在你的其他导入中添加以下声明:

declare let window;

此博客文章中提供了有关此内容的简短说明。

于 2018-02-26T18:02:50.977 回答