I have an Angular application that works fine via the ng serve. The application also builds correctly via ng build --prod, but when I run the generated sources in the browser I get a following error:
TypeError: $m.Subject is not a constructor
at new e (error-handling.service.ts:8)
at core.js:21140
at Rs (core.js:21136)
at Os (core.js:21075)
at Gs.get (core.js:21628)
at pu (core.js:21997)
at du (core.js:21876)
at su (core.js:21753)
at Xd (core.js:30266)
at Yd (core.js:30175)
at Object.dh [as createRootView] (core.js:30688)
at Ns.create (core.js:21357)
at io.create (core.js:19158)
at e.bootstrap (core.js:28031)
at core.js:27742
at Array.forEach (<anonymous>)
at e._moduleDoBootstrap (core.js:27742)
at core.js:27712
at l.invoke (zone-evergreen.js:364)
at Object.onInvoke (core.js:27149)
at l.invoke (zone-evergreen.js:363)
at i.run (zone-evergreen.js:123)
at zone-evergreen.js:857
at l.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27137)
at l.invokeTask (zone-evergreen.js:398)
at i.runTask (zone-evergreen.js:167)
at m (zone-evergreen.js:569)
The error-handling.service.ts looks like below:
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
@Injectable({
providedIn: "root",
})
export class ErrorHandlingService {
private errors: Subject<string[]> = new Subject(); // <-- error in this line
constructor() {}
public addErrors = (errors: string[]): void => this.errors.next(errors);
public getErrors = () => this.errors.asObservable();
}
The code worked fine on Angular 9 after I've upgraded the project to 10 (which also upgraded TypeScript) it has stopped working.
It's a bit confusing why it works via ng serve and crashes when I run in production. Also, why this error is not caught during compilation?
Ivy is disabled for my project.
The issue is definitely your import. Subject needs to be imported from rxjs.
import { Subject } from "rxjs";
There was an entire rxjs-compat module, even which would allow something like this. I'm pretty sure all this backwards compatibility supports has been dropped. This basically came from rxjs v5. I'm guessing you are somehow using rxjs v7 now, and they are definitely dropping it there.
You can read more about this here. You can see that Subject needs to be imported from rxjs directly. If your linters are complaining, these rules really need to be updated, because rxjs v6 has been released more than 2 years ago
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With