在库模块中定义APP_INITIALIZER时,构建失败,并且不支持Lambda错误.导出函数
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 { }
dev和prod都会抛出构建错误.
import { NgModule,APP_INITIALIZER } from '@angular/core'; import { MylibComponent } from './mylib.component'; @NgModule({ providers: [ { provide: APP_INITIALIZER,useFactory() { return () => console.log('Hi from ES6 object method shorthand') } } ] }) export class MylibModule { }
这会传递dev和prod构建,但app会抛出ERROR TypeError:当使用prod标志构建库和app时,this.appInits [r]在运行时不是函数错误.
如何在库中正确使用APP_INITIALIZER而不会出现构建或运行时错误?
复制品可以在here找到:
> git clone https://github.com/samherrmann/angular-sandBox.git
> cd angular-sandBox
> git checkout lambda-not-supported
> npm安装
> npm run build
关于这个问题的GitHub问题可以在here找到.
解决方法
我理解的是,在编译时,typescript编译器会尝试尽可能多地解析.
所以当你这样做的时候:
export function myLibInit() { return () => console.log('Hi from exported function'); }
它试图将其解析为简单的()=> console.log(‘来自导出的函数’);因为在函数中没有做任何其他事情.
现在,让我们让函数再做一点:
export function myLibInit() { var x = 2+2; //let us just do something to keep this original function return () => console.log('Hi from exported function'); }
这个编译没有错误,因为它没有返回唯一和正确的lamda函数.
下面的一个也可以,因为有一个额外的任务.
export function myLibInit() { var x = () => console.log('Hi from exported function'); return x; }
你当然可以回复一个承诺.
我确实看到了你的一些教程的链接,他们正在完成你所遇到的问题,我认为他们可能已经老了或者你正在使用的角度版本没有完成.因为文件明确指出了这一点
“The compiler does not currently support function expressions or
lambda functions. “
而且他们有点类似.一个原因可能是他们实际上从未执行构建,因为它不会给你服务错误
我可以看到他们已经在github关闭了你的问题,但我认为他们应该审查它,因为我的上述解释.