HashLocationStrategy和角度4的查询参数

时间:2017-09-25 01:53:34

标签: angular

我正在将现有的角度4应用从PathLocationStrategy迁移到HashLocationStrategy,并且需要保持入口点网址正常工作。它看起来像www.test.com/?param1=123

问题是,只要我将其切换到HashLocationStrategy,就无法通过activatedRoute.queryParams访问查询参数。 (www.test.com/#/?param1=123工作正常,但我还需要保留原始网址条目)

那么有没有办法从www.test.com/?param1=123获得HashLocationStrategy的param1值?我真的不想创建一个空的着陆页,它会重定向到www.test.com/#/?param1=123,除非我无法避免。

1 个答案:

答案 0 :(得分:1)

由于HashLocationStrategy已被用作默认值,因此应另外注入PathLocationStrategy以获取真实的浏览器位置:

  providers: [
    PathLocationStrategy,
    {provide: LocationStrategy, useClass: HashLocationStrategy},
    ...
  ]

...

class AppComponent {
  constructor(router: Router, pathLocationStrategy: PathLocationStrategy) {
    const basePath = pathLocationStrategy.getBaseHref();
    const absolutePathWithParams = pathLocationStrategy.path();

    if (basePath !== absolutePathWithParams) {
      router.navigateByUrl(absolutePathWithParams);
    }
  }
}

如果有基本网址,则应另外将其从路径中删除。