2

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!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I'll try this out asap and let you know.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.