Skip to content

AoT error with @Inject and interface type #12631

Closed

Description

@jeffbcross

I'm submitting a ... (check one with "x")

[x] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

I have a constructor that uses @Inject to get a dependency, and references an interface for that the dep, constructor( @Inject(FirebaseApp) _fbApp: firebase.app.App). When I compile the lib with ngc, I get this error:

Error: angularfire2/src/auth/firebase_sdk_auth_backend.ts:27:1: Error encountered in metadata generated for exported symbol 'FirebaseSdkAuthBackend':
 angularfire2/src/auth/firebase_sdk_auth_backend.ts:30:45: Metadata collected contains an error that will be reported at runtime: Expression form not supported.
  {"__symbolic":"error","message":"Expression form not supported","line":29,"character":44}
    at angularfire2/node_modules/@angular/tsc-wrapped/src/collector.js:514:27
    at Array.forEach (native)
    at validateMetadata (angularfire2/node_modules/@angular/tsc-wrapped/src/collector.js:502:42)
    at MetadataCollector.getMetadata (angularfire2/node_modules/@angular/tsc-wrapped/src/collector.js:374:17)
    at MetadataWriterHost.writeMetadata (angularfire2/node_modules/@angular/tsc-wrapped/src/compiler_host.js:111:51)
    at MetadataWriterHost.writeFile (angularfire2/node_modules/@angular/tsc-wrapped/src/compiler_host.js:103:19)
    at Object.writeFile (angularfire2/node_modules/typescript/lib/typescript.js:45364:132)
    at Object.writeFile (angularfire2/node_modules/typescript/lib/typescript.js:7597:14)
    at writeEmittedFiles (angularfire2/node_modules/typescript/lib/typescript.js:37854:20)
    at doEmit (angularfire2/node_modules/typescript/lib/typescript.js:37714:17)

If I change the type to any, compilation succeeds.

Expected behavior

I would expect to be able to reference an interface in a constructor in conjunction with @Inject.

Minimal reproduction of the problem with instructions

ngc this thing:

import { NgModule, Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';

export interface Foo {}

@Injectable()
export class MyClass {
  constructor(@Inject(Http) http: Foo) {}
}

@NgModule({
  providers: [MyClass]
})
export class MyModule {}
  • Angular version: 2.0.X

@angular/[email protected]
@angular/[email protected]

  • Node (for AoT issues): node --version =

Node 5.10.1

Activity

  1. vicb commented on Oct 31, 2016

    @vicb
    Contributor
  2. self-assigned this
    on Nov 1, 2016
  3. filipesilva commented on Nov 14, 2016

    @filipesilva
    Contributor

    I am also experiencing this with @types/angular-router while upgrading an app with @angular/upgrade/static:

    @Component({
      // ...
    })
    export class PhoneDetailComponent {
      // ...
      constructor(@Inject('$routeParams')
                    $routeParams: angular.route.IRouteParamsService,
                  phone: Phone) {
    // ...
    

    Further details in #12860.

  4. psaussure commented on Dec 12, 2016

    @psaussure

    Same here by using
    @Inject(FirebaseApp) private firebaseApp: firebase.app.App

    in my constructor. I confirm the @jeffbcross error and agree we shouldn't have to type using any to get the intended behavior.

  5. ValentinFunk commented on Dec 14, 2016

    @ValentinFunk

    Getting the same thing

    export interface LazyMapsAPILoaderConfigLiteral {
      /**
       * The Google Maps API Key (see:
       * https://developers.google.com/maps/documentation/javascript/get-api-key)
       */
      apiKey?: string;
    
      /**
       * The Google Maps client ID (for premium plans).
       * When you have a Google Maps APIs Premium Plan license, you must authenticate
       * your application with either an API key or a client ID.
       * The Google Maps API will fail to load if both a client ID and an API key are included.
       */
      clientId?: string;
    }
    
    
    @Injectable()
    export class LazyMapsAPILoader extends MapsAPILoader {
      private _scriptLoadingPromise: Promise<void>;
    
      constructor(
        @Inject(LAZY_MAPS_API_CONFIG) private _config: LazyMapsAPILoaderConfigLiteral,
      ) {
        super();
        this._config = this._config || {};
      }
    //...
    }

    Fails with

    
    Failed on type {"filePath":"C:/Dev/trvlm8s/frontend/src/app/services/map/lazy-maps-api-loader.ts","name":"LazyMapsAPILoader"} with error Error: Error encountered resolving symbol value
    s statically. Could not resolve type LazyMapsAPILoaderConfigLiteral (position 106:52 in the original .ts file), resolving symbol LazyMapsAPILoader in C:/Dev/trvlm8s/frontend/src/app/se
    rvices/map/lazy-maps-api-loader.ts
    Error: Error encountered resolving symbol values statically. Could not resolve type LazyMapsAPILoaderConfigLiteral (position 106:52 in the original .ts file), resolving symbol LazyMaps
    APILoader in C:/Dev/trvlm8s/frontend/src/app/services/map/lazy-maps-api-loader.ts
    
  6. mmc41 commented on Dec 28, 2016

    @mmc41

    Getting the same thing with a test component (AOT really miss a feature to exclude things):

    export const TEST_CONFIG_TOKEN = new OpaqueToken('TestConfig');
    
    export interface TestConfig {
      ...
    };
    
    @Component({
      template: `
        ...
      `
    })
    export class TestHostComponent {
      constructor(@Inject(TEST_CONFIG_TOKEN) public config: TestConfig) {
      }
    }
    
    

    The component is only used for testing but still AOT insist it should be defined in a module (otherwise another error will occur) and when processing AOT produces this error:

    ERROR in Error encountered resolving symbol values statically. Could not resolve type TestConfig (position 100:57 in the original .ts file), resolving symbol TestHostComponent ...

    A complete blocker - could not be more serious. Only way forward is to delete all my advanced tests in order to get AOT working... NO

  7. DzmitryShylovich commented on Dec 28, 2016

    @DzmitryShylovich
    Contributor

    Only way forward is to delete all my advanced tests

    but u can just change type to any... or change interface to abstract class

  8. mmc41 commented on Dec 28, 2016

    @mmc41

    Thanks. This workaround works too. Annoying that I lose type safety here but at least I can proceed.

  9. DzmitryShylovich commented on Dec 28, 2016

    @DzmitryShylovich
    Contributor

    Annoying that I lose type safety

    I believe u can do something like

    export class TestHostComponent {
     config: TestConfig;
      constructor(@Inject(TEST_CONFIG_TOKEN) config: any) {
           this.config = <TestConfig>config;
      }
    }
    
  10. mmc41 commented on Dec 28, 2016

    @mmc41

    Yes indeed. I actually did exactly what you suggest with an additional comment referencing this bug to explain why I had to write bad code like this (it hurts to write 'any', to do type conversions and to add seemingly unnecessary lines of code ;-))

  11. oliverjanik commented on Jan 11, 2017

    @oliverjanik

    Wow this took a long time to find on Google. This is still happening in 2.4.1 using @ngtools/webpack npm package. Why does AOT even care about constructor arguments?

  12. chuckjaz commented on Jan 11, 2017

    @chuckjaz
    Contributor

    In this case it shouldn't. In general, if no @Inject() is provided, the type of the argument is the type of the instance created by the injector. This bug is tracking that non-reified (such as interfaces) are handled correctly by the collector and the static reflector.

  13. itsnotvalid commented on Jan 18, 2017

    @itsnotvalid

    Provider Alias also depend of @Inject() which produces the same error.

  14. Meligy commented on Jan 21, 2017

    @Meligy
    Contributor

    I am having this as well.

    This fails with AoT compiler in Angular CLI, because Window (the browser window) is an interface:

    export function getWindow() { return window; }
    
    @NgModule({
      declarations: [
        AppComponent,
        SimpleRouteComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule
      ],
      providers: [
        {provide: 'window', useFactory: getWindow}
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {
      constructor(@Inject('window') w: Window) {
        console.log(w);
      }
    }
    

    With error:

    ERROR in Error encountered resolving symbol values statically. Could not resolve type Window (position 29:36 in the original .ts file), resolving symbol AppModule in /Users/Meligy/Code/github/Meligy/routing-angular-cli/src/app/app.module.ts

    (More details in #14050)

    The workaround (other than using any type in the constructor) was to create a dummy class type to trick the compiler, like:

    @Injectable()
    export class WindowWrapper extends Window {
    
    }
    
    export function getWindow() { return window; }
    
    @NgModule({
      declarations: [
        AppComponent,
        SimpleRouteComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule
      ],
      providers: [
        {provide: WindowWrapper, useFactory: getWindow}
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {
      constructor(w: WindowWrapper) {
        console.log(w);
      }
    }
    
  15. 24 remaining items

  16. DzmitryShylovich commented on Mar 11, 2017

    @DzmitryShylovich
    Contributor

    #14894 the fix

  17. added a commit that references this issue on Mar 14, 2017
    b40ce9b
  18. added a commit that references this issue on Mar 15, 2017
    b00fe20
  19. MadUser commented on Mar 30, 2017

    @MadUser

    Are you sure this works with ng build --prod?
    because for me it still breaks

  20. DzmitryShylovich commented on Mar 30, 2017

    @DzmitryShylovich
    Contributor

    @MadUser it does work using plain ngc. If it doesn't work in cli then it's a cli issue

  21. mmc41 commented on Mar 30, 2017

    @mmc41

    Works fine for me with angular cli 1.0 and angular 4.0 project

  22. DzmitryShylovich commented on Mar 30, 2017

    @DzmitryShylovich
    Contributor

    @MadUser looks like it doesn't work with ts interfaces such as Window, Document etc. See #15640

  23. added a commit that references this issue on Aug 11, 2017
    b7fe0e9
  24. added a commit that references this issue on Aug 28, 2017
    45d70ae
  25. angular-automatic-lock-bot commented on Sep 11, 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.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions