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

APP_INITIALIZER in library causes "Lambda not supported" error

在库模块中定义 APP_INITIALIZER 时,构建失败并出现 Lambda not supported 错误。导出函数时抛出构建错误 as per docs:

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

devprod 都抛出了构建错误。

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

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

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

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

可以找到复制品here:

  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 有关此问题的问题可以找到 here

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

所以当你这样做的时候:

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

它试图将其解析为简单的 () => 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');
}

这个编译没有错误,因为它不是 return 唯一且准确的 lamda 函数。

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

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

你当然可以return一个承诺。

我确实看到了您指向一些教程的链接,它们正在做您遇到的问题,我认为它们可能已经过时或未完成您正在使用的 angular 版本。因为文档明确指出

"The compiler does not currently support function expressions or lambda functions. "

他们正在做的事情与此类似。一个原因可能是他们实际上从未执行过构建,因为它不会在 ng serve

上给你错误

我可以看到他们已经在 github 上关闭了您的问题,但我认为他们应该根据我的上述解释对其进行审核。

尝试在您的函数上方使用此代码示例 myLibInit()。有关详细信息,请参阅 this

/**
 * @dynamic
 */