首页 > 解决方案 > 在 Angular 7 路由中将查询字符串放在哈希之前

问题描述

我有一个更大的应用程序,其中包含一个 Angular 页面。外部应用程序使用查询字符串来存储它的一些状态(不是我的决定)。Angular 页面使用路由。

我尝试了几种方法,使用 PathLocationStrategy 并为 APP_BASE_HREF 提供我自己的提供程序,但最终得到的 url 看起来像这样:

/my-page/#/?foo=bar/my-route

当我想去:

/my-page?foo=bar#/my-route

有没有办法做到这一点?请注意,我只知道 foo=bar 在运行时。对该页面的后续访问可能会产生:

/my-page?foo=baz#/my-route 或 /my-page?foo=qux#/my-route 或 /my-page?foo=12345#/my-route

我已经尝试过,在 app.module.ts 中:


    export function getBaseLocation(): string {
      return location.toString()
        .replace(`${location.protocol}//`, '')
        .replace(location.host, '');
    }
    @NgModule({
    // ...
      providers: [{
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation,
      },
    //...
    });

在 app.component.ts 中:

  constructor(
    private pathLocationStrategy: PathLocationStrategy,
    private router: Router) {
    if (this.pathLocationStrategy.getBaseHref() !== this.pathLocationStrategy.path()) {
      this.router.navigateByUrl(this.pathLocationStrategy.path());
    }
  }

标签: angulartypescript

解决方案


推荐阅读