【问题标题】:Angular 2 AOT "Expression form not supported" errorAngular 2 AOT“不支持表达式”错误
【发布时间】:2017-01-26 13:21:35
【问题描述】:

在 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;,它会起作用。

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

【问题讨论】:

    标签: angular angular2-aot


    【解决方案1】:

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

    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 {}
    

    【讨论】:

    • 感谢您的建议,但不,它不起作用。我得到Argument of type '{ initialNavigation: false; useHash: () => boolean; }' is not assignable to parameter of type 'ExtraOptions'. Types of property 'useHash' are incompatible.。如果我尝试使用 useHash: useHash() 我会得到原始错误。
    【解决方案2】:

    您遇到的问题确实很奇怪,由于TS限制,AOT编译器在获取全貌方面有点受限,应该很快解决。

    您可以跟踪此问题以获取更新 https://github.com/angular/angular/issues/13138

    要解决您的问题,您只需在 Angular 编译器上玩一点小技巧...

    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-06-07
      • 2019-04-08
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      相关资源
      最近更新 更多