【问题标题】:Why does angular router url doesn't have the same value as window.location.href为什么角度路由器 url 与 window.location.href 的值不同
【发布时间】:2022-06-25 03:26:12
【问题描述】:

在我的网站上工作,在实例化 root 服务时必须向 api 发出一些请求。

我想根据url获取一些数据,所以我做了以下

@Injectable({
  providedIn: 'root',
})
export class MyService {

  constructor(private _router: Router) {
     this.init() 
  }

  init() {
    console.log('url', this._router.url, window.location.href)
    // this._router.url : `/`
    // window.location.href : `http://localhost:4201/my/url`
    // Here I'll make some get request with the url
  }
}

但我发现路由器还没有正确的值,或者至少不是一直都没有。

有趣的是,有时它确实有效。

我应该怎么做才能在不使用window 对象的情况下获取位置?

【问题讨论】:

    标签: javascript angular typescript angular-routing


    【解决方案1】:

    window.location.href 定义 DOM 位置,而 router.url 基于 basehref。 检查 basehref 和 RouterModule.forRoot([])

    【讨论】:

    • 如果我无法更改 baseRef,那么使用 router.url 有点不可行,对吗?
    • 您是否在 app.module.ts 导入中包含了 RouterModule.forRoot([])?
    • 是的,我做到了。关于“我无法更改 baseRef”,我的意思是我的项目不允许这样做,因为它会破坏我的应用程序中的其他逻辑。这个很好地解释了我的问题,也解决了它,连同你的答案。找到解决方案后我会更新stackoverflow.com/questions/38112891/…
    【解决方案2】:

    基本上,您使用 Angular Router 在应用程序内的页面之间进行路由,并且对于每个外部路由,您应该使用 window.location/href(html)。

    在这里回答https://stackoverflow.com/a/72514835/12677894

    window.location.href 定义 DOM 位置,而 router.url 是基于 basehref *

    【讨论】:

    • 我确实在某个地方读到过(抱歉,找不到链接),使用像 window.location.href 这样的全局变量是不安全的,因为可以在不在内部的应用程序中的其他地方导入 Angular某些浏览器,然后会在尝试读取此变量时产生错误。看起来你的回答可能会产生这样的错误,这就是我在问题中描述我不想使用这样的变量的原因
    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2015-06-13
    • 2017-04-19
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多