angular: Angular2 AoT Compiler Errors

When I try to compile my project with ngc, it throws the below error:

Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 92:25 in the original .ts file), resolving symbol AppModule in

In my App Module I have the below providers and probably this is causing the project. I am not sure what exactly is wrong with this?

providers: [
        GlobalService,
        {
            provide: Http,
            useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, globalService: GlobalService) => new HttpLoading(backend, defaultOptions, globalService),
            deps: [XHRBackend, RequestOptions, GlobalService]
        }
    ],

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 39
  • Comments: 52 (23 by maintainers)

Commits related to this issue

Most upvoted comments

pls try

export function httpFactory(backend: XHRBackend, defaultOptions: RequestOptions, globalService: GlobalService) {
  return  new HttpLoading(backend, defaultOptions, globalService);
}

providers: [
        GlobalService,
        {
            provide: Http,
            useFactory:  httpFactory,
            deps: [XHRBackend, RequestOptions, GlobalService]
        }
    ],

/cc @chuckjaz

Oh for crying out loud. So to get decent load times for Angular2 apps we need to use ngc. To use NGC, we now need every every vendor of angular2 libs to now include a .metadata.json file? So now we’re dependent on that as well?

So what are we going to do since Angular2 allows people to write components in pure JS, and since JS is not Typescript, these libraries/modules will never have a .metadat.json and thus can never be used by AOT?

I’ve tried three different ways to shrink down a angular2 app to a decent size and reduce download times by bundling stuff up into one module, and all three have been dead ends. Various, errors, poor documentation, and our app takes 10 seconds to start due to the hundreds of npm deps it loads at boot.

  • Angular-cli? Buggy. No go
  • Angular aot compiler? Not every already shipping angular2 lib has .metadata.json files
  • Rollup? Issues with libs being shipped in various incompatible module formats in npm. Some are commonjs, some amd, etc, and rollup can handle some but not others.

Is there a sane "WORKS NOW’ way to make a single js bundled app file? Even with no AOT? For a 1.0 release this is maddening.

If I were to jump through these hopes, would I finally a single file, or nearly single Angular2 app? Or do I need to find a bundler that would then work with everything else we use?

@DanielJoyce Third party libs have to be AoT-ed before they can be integrated in an AoT compiled application. The third party library should publish JS files, .d.ts files and metadata.json files

To your point about non Angular libs published as commonsJS, you can use the commonJS rollup plugin to convert commonJS to es2015.

The AoT cookbook shows how to do this for Tour of Heroes. This specific example uses the commonJS plugin to convert commonJS RxJS code

https://angular.io/docs/ts/latest/cookbook/aot-compiler.html#!#toh

@naveedahmed1 All referenced libraries must include the .metadata.json file along side any .d.ts files they produce otherwise they will not work correctly with ngc. The .metadata.json file contains the information we need that was in the original .ts file but was not included in the .d.ts file. If we don’t have that information we cannot generate the factories for the library.

Is there an equivalent to @vicb’s method when dealing with imports rather than providers? My AOT compilation trips up over AgmCoreModule.forRoot(...) below, with Error encountered resolving symbol values statically...

(Strangely it’s happy with RouterModule.forRoot(...) - why would that be? The lack of a .metadata.json perhaps?)

Thanks!

@NgModule({
  ...,
  imports: [
    RouterModule.forRoot(APP_ROUTES),
    BrowserModule,
    HttpModule,
    AgmCoreModule.forRoot({
      apiKey: environment.googleMapsApiKey
    })
  ]
});

try

{provide: APP_INITIALIZER, useFactory:initFactory, deps: [AppConfig], multi: true },
export function initFactory(config: AppConfig) {
    return () => config.load();
}

you forgot return in your step 1

None of these “solutions” are working for me…

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 12:42 in the original .ts file), resolving symbol compose in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/node_modules/@ngrx/core/src/compose.d.ts, resolving symbol compose in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/node_modules/@ngrx/core/index.d.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts
webpack: Failed to compile.

Bug Report

  • bug report I cannot understand why all issues are closed but it got me annoyed to the death… Wasted whole day on this and still cannot understand why this code is not working
@NgModule({
    imports: [CommonModule]
})
export class StoreModule {
    static provideStore(): ModuleWithProviders {
        return {
            ngModule: StoreModule,
            providers: [ added some providers]
        };
    }     
}

throwing an error:

"Calling function 'SotreModule', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule"

I compared it with RouterModule in .ts and .js all the same. Tried to many of work arounds and nothing. In dev mode all works fine, when this code is added stright to project it works fine too, but when exported as a separate package - BAM - nothing!

Anybody?

For example RouterModule:

@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
  constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any, @Optional() router: Router) {}
  static forChild(routes: Routes): ModuleWithProviders {
    return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
  }
}

If this thing will not be resolved I will not have any other way just to drop Angular support and stay only in react since this issue with ngc aot is very old.

More than that - when compiling AOT with webpack all works fine, just after upgrading to Angular 5.0.0 ngc-weback plugin is not working any more.

here is complete code of ng-state.module.ts:

import { Inject, Injector, ModuleWithProviders, NgModule, InjectionToken } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Dispatcher } from './services/dispatcher';
import { Router } from '@angular/router';
import { RouterState } from './state/router-state';
import { ServiceLocator } from './helpers/service-locator';
import { State } from './state/state';
import { StateHistory } from './state/history';
import { StateHistoryComponent } from './state/state-history';
import { Store } from './store/store';

export const INITIAL_STATE = new InjectionToken('INITIAL_STATE');
export const COLLECT_HISTORY = new InjectionToken('COLLECT_HISTORY');
export const STORE_HISTORY_ITEMS = new InjectionToken('STORE_HISTORY_ITEMS');
export const IS_PROD = new InjectionToken('IS_PROD');

export function stateFactory(initialState) {
    return new State(initialState);
}

export function storeFactory(state: State<any>) {
    return new Store(state);
}

export function historyFactory(store: Store<any>) {
    return new StateHistory(store);
}

export function routerStateFactory(store: Store<any>, router: Router) {
    return new RouterState(store, router);
}

@NgModule({
    imports: [CommonModule],
    declarations: [StateHistoryComponent],
    exports: [StateHistoryComponent]
})
export class StoreModule {
    static provideStore(initialState: any, isProd?: boolean, collectHistory?: boolean, storeHistoryItems?: number): ModuleWithProviders {
        return {
            ngModule: StoreModule,
            providers: [
                { provide: STORE_HISTORY_ITEMS, useValue: storeHistoryItems },
                { provide: COLLECT_HISTORY, useValue: collectHistory },
                { provide: INITIAL_STATE, useValue: initialState },
                { provide: IS_PROD, useValue: isProd },
                { provide: State, useFactory: stateFactory, deps: [INITIAL_STATE] },
                { provide: Store, useFactory: storeFactory, deps: [State] },
                { provide: StateHistory, useFactory: historyFactory, deps: [Store, INITIAL_STATE] },
                { provide: RouterState, useFactory: routerStateFactory, deps: [Store, Router] },
                Dispatcher
            ]
        };
    }

    constructor(
        injector: Injector,
        stateHistory: StateHistory,
        routerState: RouterState,
        @Inject(INITIAL_STATE) initialState: any,
        @Inject(STORE_HISTORY_ITEMS) storeHistoryItems: any,
        @Inject(COLLECT_HISTORY) collectHistory: any,
        @Inject(IS_PROD) isProd: any
    ) {
        if (storeHistoryItems !== undefined) {
            StateHistory.collectHistory = collectHistory;
        }

        if (collectHistory !== undefined) {
            StateHistory.storeHistoryItems = storeHistoryItems;
        }

        ServiceLocator.injector = injector;
        stateHistory.init(initialState);
        routerState.init();

        if (!isProd) {
            (<any>window).state = StateHistory;
        }
    }
}

I have same issue in shrard.module.ts file , throw the same error Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol SharedModule in

my app.module.ts is like below

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserModule,
        HttpModule,
        MdToolbarModule,
        MdSidenavModule,
        routing,
        SharedModule,
        ProjectModule,
        ConsumerAppModule,
        UserModule,
        ChangePasswordModule
    ],
    bootstrap: [AppComponent],
    providers: [HttpService, LoginService, LoaderService, { provide: LocationStrategy, useClass: HashLocationStrategy }, UserRole],
})
export class AppModule { }

and my shared.module.ts like below

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        MdButtonModule.forRoot(),
        MdToolbarModule.forRoot(),
        MdSidenavModule.forRoot(),
        MdInputModule.forRoot(),
        MdCheckboxModule.forRoot(),
        Md2Module.forRoot()
    ],
    declarations: [],
    exports: [CommonModule, FormsModule, MdButtonModule, MdToolbarModule, MdInputModule, MdCheckboxModule, Md2Module]
})
export class SharedModule { }

I have not got a proper solution so please suggest to me

Thank you so much @vicb that actually fixed the error. But now I am having another issue.

In my project I am using ng2-charts (https://github.com/valor-software/ng2-charts) but now when I try to compile my project with Angular 2 Ahead of Time Compilation (AoT) using ngc it throws below error:

Error: Unexpected value 'CHART_DIRECTIVES' declared by the module 'AppModule'

Despite of the fact that I have imported CHART_DIRECTIVES in AppModule and added it to declarations .

Same error with CKEditorComponent (https://github.com/chymz/ng2-ckeditor)

Im having the same issue with Angular 4.4.5.
I’ve tried many different configurations -

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [ UserComponent ],
  declarations: [ UserComponent ]
})
export class SecurityModule {

  static forRoot(securityService: ISecurityService): ModuleWithProviders {
    console.log('Creating SecurityModule instance forRoot with service:', securityService);
    return {
      ngModule: SecurityModule,
      providers: [{
        provide: SECURITY_SERVICE,
        useValue: securityService
      }]
    };
  }

  constructor (@Optional() @SkipSelf() parentModule: SecurityModule) {
    if (parentModule) {
      throw new Error(
        'SecurityModule is already loaded. Import it in the AppModule only');
    } else {
      console.log('Creating SecurityModule instance for child');
    }
  }
}

Error: Error: Error encountered resolving symbol values statically. Calling function ‘SecurityModule’, function calls are not supported. Consider replacing the function or lambda with a reference to an exported function,

@DzmitryShylovich It worked, this approach worked:

{provide: APP_INITIALIZER, useFactory:initFactory, deps: [AppConfig], multi: true }, export function initFactory(config: AppConfig) { return () => config.load(); }

Thanks a ton, you saved couple of days of my effort. I was looking at this issue from long time. Thank you.

I have converted my sample app to use AOT and tree shaking. I noticed that using TypeScript (tsc) for the transpilation from esm to es5 was very slow, so I switched to babel.

Here is my demo app running AOT/tree shaken code. http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

Source here: https://github.com/thelgevold/angular-2-samples

Just follow the trail from package.json to see the steps I am using to AOT/shake.

@chuckjaz I don’t see any .metadata.json file under node_modules\ng2-charts directory. I am not able to compile my project with any of the third part plugin. Is this any special file that the every third party plugin should have?

You can’t use anonymous functions or online lambdas. Anything that uses a lambda for wiring services, you need to lift that lambda out, turn it into a named function and call it instead.

The next question is why aot can’t do this…

On Sat, Feb 4, 2017, 07:56 Jim Lynch notifications@github.com wrote:

None of these “solutions” are working for me…

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 12:42 in the original .ts file), resolving symbol compose in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/node_modules/@ngrx/core/src/compose.d.ts, resolving symbol compose in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/node_modules/@ngrx/core/index.d.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol reducers in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/state-management/reducers/root-reducer.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts, resolving symbol AppModule in /Users/jameslynch/Git-Projects/t2-2/t2/CypherApp/src/app/app.module.ts webpack: Failed to compile.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/angular/angular/issues/11262#issuecomment-277454777, or mute the thread https://github.com/notifications/unsubscribe-auth/AA50lsW-rPoEnWgIskj3Mpzx3AcWmTMwks5rZJ-_gaJpZM4JzSyy .

– Daniel Joyce

The meek shall inherit the Earth, for the brave will be among the stars.

@anvesh48 and others who want to use AOT, you could check https://github.com/rangle/angular-2-aot-sandbox for AoT Do’s and Don’ts

@jordivila AOT only supports a limited subset of JavaScript which it can evaluate. I have some preliminary documentation for the subset here. In your example, the StaticReflector cannot create an instance of RouteDataCustomized at compile time.

tried lambada with same issue in latest 1.24 ng-cli

ERROR in Error encountered resolving symbol values statically. Calling function 'MsLibModule', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in C:/msweb/Angular-kitchen-sink/src/app/app.module.ts, resolving symbol AppModule in C:/msweb/Angular-kitchen-sink/src/app/app.module.ts

might be ok…

@robwormald is a build wizard, he’ll be able to help you much much more than me.

@Sukh9212 regarding your paths issue, I would suggest using relative paths please visit https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html for details