【问题标题】:Circular dependency with Angular 2 and SystemJS [duplicate]Angular 2和SystemJS的循环依赖[重复]
【发布时间】:2016-03-29 08:11:02
【问题描述】:

我有一个我认为是由循环依赖引起的问题。经过一些广泛的研究,我一直无法找到解决方案。它看起来与这个问题有关:TypeScript 中的TypeError: b is undefined in __extends,但它对我没有帮助。

我已经能够简化this plunker 中的问题。

基本上有3个类:

  • A,包含A 的数组
  • B,继承自A
  • F 类,可以根据值创建AB 的工厂

这样做的目的是处理一个可以是动态的参数列表(每个A 是一个参数并且可以是一个数组),其中BA 处理文件的特化。我尝试删除工厂,但只有AB 我仍然得到同样的错误:

TypeError: b is undefined Error loading http://localhost:3000/app/main.js

这是a.ts

的代码
import { F } from './f';

export class A {
  children: A[]

  constructor(hasChildren: boolean = false) {
    if (hasChildren) {
      for (var i = 0 ; i < 10 ; ++i) {
        let isB = (Math.random() * 2) > 1;
        this.children.push(F.createObject(isB))
      }
    }
  }
}

b.ts

import { A } from './a';

export class B extends A {
}

f.ts

import { A } from './a'
import { B } from './b'

export class F {
  static createObject(isB: boolean): A {
    if (isB) {
      return new B
    } else {
      return new A
    }
  }
}

【问题讨论】:

  • 错误信息中提到的b所在的行在哪里?
  • 在 JavaScript 控制台中。实际上如果类被命名为tototata 错误信息仍然是TypeError: b is undefined Error loading http://localhost:3000/app/main.js
  • Plunker 链接对我不起作用。
  • 对我来说也不是...我会在 2 分钟内更改链接,我正在做一个没有工厂的 plunker。
  • 确实是上面链接的副本。只需将两个类放在同一个文件中即可,谢谢。如果可以提供帮助,这是工作的 plunker:plnkr.co/edit/fi2MAGeA7MjdqewZcyjb

标签: typescript angular systemjs


【解决方案1】:

您不能以这种方式进行循环依赖。您可以使用界面来解决问题

Plunker example

tata.ts

import { IToto } from './itoto';


export class Tata implements IToto {
  children: Toto[]
}

toto.ts

import { Tata } from './tata';
import { IToto } from './itoto';

export class Toto implements IToto{
  children: Toto[] = [];

  constructor(hasChildren: boolean = false) {
     ...
  }
}

itoto.ts

export interface IToto {
  children: Toto[]
}

另见Circular dependency injection angular 2

【讨论】:

猜你喜欢
  • 2016-02-27
  • 1970-01-01
  • 2017-12-16
  • 2017-10-09
  • 2017-05-05
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多