库中的APP_INITIALIZER导致"Lambda not supported"错误

Sam*_*ann 5 angular-cli angular ng-packagr

APP_INITIALIZER在库模块中定义时,构建将失败并显示Lambda not supported错误.按照文档导出函数时抛出构建错误:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { MylibComponent } from './mylib.component';

export function myLibInit() {
  return () => console.log('Hi from exported function');
}

@NgModule({
  providers: [
    {
      provide: APP_INITIALIZER,
      multi: true,
      useFactory: myLibInit
    }
  ]
})
export class MylibModule { }
Run Code Online (Sandbox Code Playgroud)

构建误差均投掷devprod.

我也尝试使用ES6对象方法简写符号来定义工厂函数:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { MylibComponent } from './mylib.component';

@NgModule({
  providers: [
    {
      provide: APP_INITIALIZER,
      multi: true,
      useFactory() {
        return () => console.log('Hi from ES6 object method shorthand')
      }
    }
  ]
})
export class MylibModule { }
Run Code Online (Sandbox Code Playgroud)

这会传递devprod构建,但是ERROR TypeError: this.appInits[r] is not a function当使用prod标志构建库和应用程序时,应用程序会在运行时抛出错误.

如何APP_INITIALIZER在库中正确使用它而不会出现构建或运行时错误?

可以在这里找到复制品:

  1. git clone https://github.com/samherrmann/angular-sandbox.git
  2. cd angular-sandbox
  3. git checkout lambda-not-supported
  4. npm install
  5. npm run build

关于这个问题的GitHub问题可以在这里找到.

Ere*_*Dev 10

我理解的是,在编译时,typescript编译器会尝试尽可能多地解析.

所以当你这样做的时候:

export function myLibInit() {
  return () => console.log('Hi from exported function');
}
Run Code Online (Sandbox Code Playgroud)

它试图解决它只是() => console.log('Hi from exported function');因为在函数中没有做任何其他事情.

现在,让我们让函数再做一点:

export function myLibInit() {
  var x = 2+2; //let us just do something to keep this original function
  return () => console.log('Hi from exported function');
}
Run Code Online (Sandbox Code Playgroud)

这个编译没有错误,因为它没有返回唯一和正确的lamda函数.

下面的一个也可以,因为有一个额外的任务.

export function myLibInit() {
  var x = () => console.log('Hi from exported function');
  return x;
}
Run Code Online (Sandbox Code Playgroud)

你当然可以回复一个承诺.

我确实看到了你的一些教程的链接,他们正在完成你所遇到的问题,我认为他们可能已经老了或者你正在使用的角度版本没有完成.因为文件明确指出了这一点

"编译器目前不支持函数表达式或lambda函数."

而且他们有点类似.一个原因可能是他们实际上从未执行过构建,因为它不会给你带来错误ng serve

我可以看到他们已经在github上关闭了你的问题,但我认为他们应该审查它,因为我的上述解释.