pesche666
pesche666

Reputation: 179

Cant inject angular provider declared with useClass

I have a global error handler class

@Injectable()
export class ErrorHandlerService implements ErrorHandler {

  // error stream others can subscribe to
  errors$ = new Subject<ClientError>();

  ...
}

I register it in app.module.ts with:

...
{provide: ErrorHandler, useClass: ErrorHandlerService},
...

Now I want to inject the error handler into other services so that they can subscribe to errors$, but I get an Error: NullInjectorError: No provider for ErrorHandlerService!. If I add providedIn: root in ErrorHandlerService, injection works but the ErrorHandler gets instantiated twice which will lead to problems since I have suddenly two errors$ streams. How can I avoid this double instantiation?

Upvotes: 1

Views: 1203

Answers (1)

Thomas Renger
Thomas Renger

Reputation: 1044

You want to inject ErrorHandlerService or ErrorHandler and in both cases you want to inject the same class (ErrorHandlerService)?

Well, your example shows how to define a class for ErrorHandler but not for ErrorHandlerService.

So try useExisting and inject ErrorHandlerService in root.

Upvotes: 2

Related Questions