Angular Compiler throws Internal error: unknown identifier {}

浪子不回头ぞ 提交于 2021-01-27 18:52:31

问题


I am constructing my angular2 services like so

import { OpaqueToken, ClassProvider } from "@angular/core";

export interface IService {
  // ... interface declaration
}

export class Service implements IService {
  // ... implementation goes here
}

export const IService = new OpaqueToken(Service.name);

export const ServiceProvider: ClassProvider = {
    provide: IService,
    useClass: Service,
};

This has worked and compiled wonderfully using ngc with angular 2.x.x But after upgrading to angular 4.x.x, the ServiceProvider can no longer be ngc-compiled when used in a components 'providers' array. (Interestingly, the whole thing works when the provider is registered in an ngModule and NOT in a component.)

I get the following on my console:

events.js:160 throw er; // Unhandled 'error' event ^ Error: Command failed: npm run ngc Error: Internal error: unknown identifier {}

Any ideas what's going on? I might convert my service to @Injectable() and not use the interface but that seems to run counter to the whole idea of using service interfaces :(

F.Y.I: I am using TypeScript 2.2.2

Thanks a lot for your help!


回答1:


https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html

OpaqueToken was deprecated in 4.x, maybe try using the InjectionToken instead.

That's the first thing that came to mind.




回答2:


Unfortunately, replacing OpaqueToken with InjectionToken did not solve the issue. What did however, was using abstract classes instead of interfaces and injection tokens.

According to this answer Angular 2 Injectable Interface? it is a common recipe (also used by the angular team itself) to inject abstract classes and use them like interfaces.

import { ClassProvider } from "@angular/core";

export abstract class IService {
  // ... interface declaration
}

export class Service implements IService {
  // ... implementation goes here
}

export const ServiceProvider: ClassProvider = {
    provide: IService,
    useClass: Service,
};


来源:https://stackoverflow.com/questions/43850902/angular-compiler-throws-internal-error-unknown-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!