Skip to content

Angular2 AoT Compiler Errors #11262

Closed
Closed

Description

@naveedahmed1

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]
        }
    ],

Activity

  1. vicb commented on Sep 2, 2016

    @vicb
    Contributor

    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

  2. naveedahmed1 commented on Sep 2, 2016

    @naveedahmed1
    ContributorAuthor

    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)

  3. chuckjaz commented on Sep 2, 2016

    @chuckjaz
    Contributor

    Does ng2-charts have .metadata.json files?

    Error: Unexpected value... could be an indication that we could not find the metadata for the module that declared CHART_DIRECTIVES.

  4. naveedahmed1 commented on Sep 2, 2016

    @naveedahmed1
    ContributorAuthor

    @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?

  5. singhjusraj commented on Sep 2, 2016

    @singhjusraj

    I'm having the same CHART_DIRECTIVES issue with ngc

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

    as @naveedahmed1 said, I don't see any .metadata.json files
    If a plugin doesn't have this file how do I make it happen?

  6. singhjusraj commented on Sep 2, 2016

    @singhjusraj

    With ngc I'm also having Resource file not found: issues where it doesn't load my html template files

    in the component, I have..

    @Component({ selector: 'my-dashboard', templateUrl: 'app/Home/home.component.html' })

    while compiling with ngc I get

    Error: Compilation failed. Resource file not found: C:/Users/sukhdeep/Documents/Angular/gd_dev_server/app/Home/app/Home/home.component.html

    See that in the path there is /app/Home/app/Home/
    I should just be /app/Home/

    How do I resolve this?

    It's just weird issue with file paths.

    My tsconfig.json is:

    { "compilerOptions": { "target": "es5", "module": "system", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false, "rootDir": "./" }, "angularCompilerOptions": { "genDir": "./ngfactory" } }

    I have absolutely no problems in JIT

  7. naveedahmed1 commented on Sep 2, 2016

    @naveedahmed1
    ContributorAuthor

    @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

  8. singhjusraj commented on Sep 2, 2016

    @singhjusraj

    @naveedahmed1 thanks. Paths issue resolved now

  9. naveedahmed1 commented on Sep 2, 2016

    @naveedahmed1
    ContributorAuthor

    @vicb @chuckjaz I am able to compile project after commenting out external plugins. ngc has generated ngfactory folder and ngfactory files in it for my application.

    But now when I updated my main.ts file by following the instructions at http://angularjs.blogspot.com/ and tried to run my application. It seems that Typescript compile is stuck. Its been several minutes and its still running. Furthermore the ngfactory folder has a size of around 11mb, is it normal?

    My above errors also still needs your attention and guidance.

  10. chuckjaz commented on Sep 2, 2016

    @chuckjaz
    Contributor

    @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.

  11. naveedahmed1 commented on Sep 2, 2016

    @naveedahmed1
    ContributorAuthor

    @chuckjaz thank you so much for your reply. Is there any guideline about how to product that file?

    Secondly is it okay to have ngfactory (folder containing factories) with size over 11 mb?

  12. chuckjaz commented on Sep 2, 2016

    @chuckjaz
    Contributor

    @naveedahmed1 The .metadata.json files are produced automatically by ngc. They should be built and delivered by the library vendor and require the .ts files.

    As for the 11mb factories maybe @tbosch would have better insight into that.

  13. thelgevold commented on Sep 3, 2016

    @thelgevold
    Contributor

    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.

  14. robhogan commented on Sep 10, 2016

    @robhogan

    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
        })
      ]
    });
  15. 28 remaining items

  16. anrepppp commented on Feb 1, 2017

    @anrepppp

    got the same error after changing it that way, but thanks for replying to my question.

    vendor.bundle.js:168420 Unhandled Promise rejection: appInits[i] is not a function ; Zone: ; Task: Promise.then ; Value: TypeError: appInits[i] is not a function(…) TypeError: appInits[i] is not a function
    at new ApplicationInitStatus

  17. anrepppp commented on Feb 1, 2017

    @anrepppp

    @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.

  18. tytskyi commented on Feb 1, 2017

    @tytskyi

    @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

  19. anrepppp commented on Feb 1, 2017

    @anrepppp

    Thanks, @tytskyi it is very useful.

  20. JimLynchCodes commented on Feb 4, 2017

    @JimLynchCodes

    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.
    
  21. DanielJoyce commented on Feb 4, 2017

    @DanielJoyce
  22. kenisteward commented on May 10, 2017

    @kenisteward

    @chuckjaz I've recently encountered a generated library that did not have metadata.json attached to it. It did, however, have the original TS files for the library. It was able to compile under AoT conditions perfectly. This leads me to believe instead of compiling myself under ngc I could just have a bigger package and deploy the ts code myself. Is this true?

    Note: I understand that if i don't compile it down that JS writers would not be able to use my library unless they compiled the TS down first.

  23. vytautas-pranskunas- commented on Nov 2, 2017

    @vytautas-pranskunas-

    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;
            }
        }
    }
  24. chaosmonster commented on Nov 3, 2017

    @chaosmonster

    I think this has nothing to do with this or any issue. I think you should ask this question at stack overflow

  25. jdbranham commented on Nov 6, 2017

    @jdbranham

    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,

  26. Toxicable commented on Nov 6, 2017

    @Toxicable

    @jdbranham remove the console.log

  27. jdbranham commented on Nov 6, 2017

    @jdbranham

    I removed the console logging but it still fails. This is the module + usage of the module -

    import { ISecurityService } from './ISecurity.service';
    import { NgModule, ModuleWithProviders, Optional, SkipSelf, InjectionToken } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { UserComponent } from './user/user.component';
    
    export const SECURITY_SERVICE = new InjectionToken<ISecurityService>('security.service');
    
    @NgModule({
      imports: [
        CommonModule
      ],
      exports: [ UserComponent ],
      declarations: [ UserComponent ]
    })
    export class SecurityModule {
    
      static forRoot(securityService: ISecurityService): ModuleWithProviders {
        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');
        }
      }
    }
       
    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppComponent } from './app.component';
    import { SecurityModule, SecurityMockService } from '@savantly/ngx-security';
    
    export const mockSecurity = new SecurityMockService();
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        SecurityModule.forRoot(mockSecurity)
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    
  28. jdbranham commented on Nov 6, 2017

    @jdbranham
  29. angular-automatic-lock-bot commented on Sep 12, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  30. locked and limited conversation to collaborators on Sep 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corehotlist: error messages

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions