kazanDipi
kazanDipi

Reputation: 85

angular2 build issue useFactory with function

As a beginner in angular, I am running across an issue whilst trying to build my app via angular-cli.

After following this tutorial:

My appModule looks like:

...
providers: [
{ provide: HttpService, useFactory: (backend: XHRBackend, options:     RequestOptions) => {
return new HttpService(backend, options); },
  deps: [XHRBackend, RequestOptions]}
]
...

When building it I get:

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 63:39 in the original .ts file), resolving symbol Ap
pModule in ../angular/app/src/app/app.module.ts
at positionalError (..\angular\app\node_modules\@angular\compiler-c
li\src\static_reflector.js:595:18)

When I use ng serve the app works without any problems.

Upvotes: 3

Views: 1183

Answers (3)

Rares Matei
Rares Matei

Reputation: 286

Try this:

export function httpServiceFactory(backend: XHRBackend, options: RequestOptions) {
  return new HttpService(backend, options);
}  
  
providers: [
  { 
    provide: HttpService, 
    useFactory: httpServiceFactory,
    deps: [XHRBackend, RequestOptions]
  }
]

When you're building it's trying to do AoT compilation which fails when encountering the lambda function, so you need to export it. While when using ng-serve it's using JiT compilation.

See: https://github.com/angular/angular/issues/11262#issuecomment-244266848

Upvotes: 6

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657741

Instead of an inline function, use an explicit function:

function httpFactory(backend: XHRBackend, options: RequestOptions) {
  return new HttpService(backend, options);
}
...
providers: [{ provide: HttpService, useFactory: httpFactory,
                deps: [XHRBackend, RequestOptions]}
]
...

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 209052

I've seen this before, and not really sure what causes this error (i.e. why it works in some cases and others it doesn't), but you can resolve it by doing what the error says: "Consider replacing the function or lambda with a reference to an exported function".

export function httpFactory(backend: XHRBackend, options: RequestOptions) {
  return new HttpService(backend, options);
}

...

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

Upvotes: 1

Related Questions