3

我有一个 Angular 应用程序,可以通过ng serve. 该应用程序也通过 正确构建ng build --prod,但是当我在浏览器中运行生成的源时,我收到以下错误:

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)

error-handling.service.ts如下所示:

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();
}

在我将项目升级到 10(也升级了 TypeScript)后,代码在 Angular 9 上运行良好,它已经停止工作。当我在生产中运行时,
为什么它会通过并崩溃,这有点令人困惑。ng serve另外,为什么在编译过程中没有发现这个错误?

我的项目禁用了 Ivy。

4

1 回答 1

3

问题肯定是你的进口。Subject需要从rxjs.

import { Subject } from "rxjs";

有一个完整的rxjs-compat模块,即使它允许这样的事情。我很确定所有这些向后兼容性支持都已被删除。这基本上来自 rxjs v5。我猜你现在正在以某种方式使用 rxjs v7,他们肯定会把它放在那里。

您可以在此处阅读有关此内容的更多信息。可以看到Subject需要rxjs直接导入。如果你的 linter 在抱怨,这些规则真的需要更新,因为 rxjs v6 已经发布了 2 年多了

于 2020-07-10T08:26:11.863 回答