1

在 Angular 2 中,我只想将哈希策略用于 IE9。为此,我将路由器配置为仅在检测到 IE9 浏览器时才使用哈希策略。

这在使用 tsc 编译时有效:

const useHash: boolean = (typeof window.history.pushState) !== 'function';

@NgModule({
  declarations: [AppComponent],
  imports: [
    RouterModule.forRoot(appRoutes, {initialNavigation : false, useHash : useHash})
  ]
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

但是 ngc 编译器(AOT 编译)不接受它。ngc 抛出以下错误(在 const 声明行)。

静态解析符号值时遇到错误。不支持表达式形式

我也尝试过(基于这篇文章:https ://medium.com/@isaacplmann/making-your-angular-2-library-statically-analyzable-for-aot-e1c6f3ebedd5#.h4pnszi13 ):

@NgModule({
  declarations: [AppComponent],
  imports: [
      RouterModule.forRoot(appRoutes, {initialNavigation : false, useHash : AppModule.useHash})
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
  static useHash: boolean = (typeof window.history.pushState) !== 'function';
}

但是我得到了同样的错误(这次在提供者行上)。请注意,如果我这样做,它会起作用static useHash: boolean = false;

如何解决模块声明的问题?

4

2 回答 2

0

The problem you have is indeed strange, the AOT compiler is a bit limited in getting the full picture because of TS limitation that should be solved soon.

You can track this issue for updates https://github.com/angular/angular/issues/13138

To workaround your issue you just need to play a little trick on the angular compiler...

const rConfig = { useHash: true, preloadingStrategy: PreloadAllModules };
rConfig.useHash = (typeof window.history.pushState) !== 'function';


@NgModule({
  declarations: [AppComponent],
  imports: [
    RouterModule.forRoot(appRoutes, rConfig)
  ]
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
于 2017-01-26T05:21:35.303 回答
0

如果您只是导出useHash函数(从第一个代码片段),它应该可以工作。请参阅下面的代码片段:

export function useHash() {
  return (typeof window.history.pushState) !== 'function';
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    RouterModule.forRoot(appRoutes, {initialNavigation : false, useHash : useHash})
  ]
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
于 2016-11-14T13:36:51.267 回答