13

Below if I import Entity I get the posts's subject error (TypeError: Object prototype may only be an Object or null: undefined), but if I replace the import with the actual Entity declaration the code runs fine.

Stackblitz demo here.

This is Customer.ts in the form that produces the error when I run the code with ts-node:

index.ts

export { Customer } from "./Customer";
export { Entity } from "./Entity";

Customer.ts

import { Entity } from "./index";

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}

Entity.ts

export abstract class Entity {
  id?: string;
}    

Run.ts (The test code)

import {Customer} from "./";

let c = new Customer({
  name: "Bob"
});
console.log(c);

If I replace the Entity import with the declaration like this:

export abstract class Entity {
  id?: string;
}    

export class Customer extends Entity {
  sku: string;
  constructor(po: any) {
    super();
    this.sku = po.sku;
  }
}

Then Run.ts logs this:

Customer { sku: undefined }

In other words it runs fine and produces no errors. Thoughts?

4

2 回答 2

24

正如我所怀疑的,您的原始程序具有循环导入。 Run.ts进口index.ts,进口Customer.tsindex.ts再次进口。由于index.tsis 已经在加载过程中并且它本身依赖于Customer.ts,因此只是将of (尚未设置)import { Entity } from "./index";绑定到of ,即使没有完成加载,也会继续执行。然后在您尝试扩展它时未定义。您可能会争辩说循环导入应该是一个错误,或者 JavaScript 引擎应该使用其他一些可以正确处理您的场景的算法;我没有资格评论为什么选择当前的设计。(其他人可以随意添加有关此的信息。)Entityindex.tsEntityCustomer.tsindex.tsEntity

如您所见,更改Customer.ts./Entity直接导入而不是./index中断循环,并且一切都按预期工作。另一种解决方案是颠倒index.ts.

于 2018-11-02T17:42:12.023 回答
-5

您可以尝试此命令并检查应用程序:

  1. ng update @angular/cli @angular/core --force
  2. npm install
  3. ng serve -o
于 2019-09-14T09:32:23.337 回答