Angular 中递归对象(通过调用静态方法链接)中的循环依赖

Ati*_*ris 6 typescript angular-cli angular angular6 angular7

如果我从类递归调用方法,是否可以在单独的文件中创建树/递归对象并避免Circular dependency detected使用Angular CLI发出警告?

(在 angular 7 中测试)我知道这是依赖注入(文章)中的一个问题,但是作为构造函数用于来自外部 api 的数据或用于内部目的的对象呢?如果无论如何这都不是一个好主意,你如何解决它?(我想这个“子问题”的答案是模型的变化,那么我应该如何修改我的模型?)我寻找解决方案,但最接近的问题并没有帮助我将相同的方法应用于我的情况。

我有EmailsAttachments(带有附件的电子邮件 - 带有附件的整个电子邮件Email也可以是附件,Attachment是具有属性的分隔对象,内容可以是FileEmail,但在这里,为简单起见,假设附件始终为 1Email或 null)。
每个类都有用于从 JSON 对象创建实例的静态方法(我从 API 获取 JSON,然后我将通过调用fromJson顶级对象上的静态方法来创建表示 API 值的对象实例):

文件:app/model/email.ts(部分代码)

import { Attachment } from './attachment';

export class Email {
  // some attributes
  public attachment?: Attachment;

  public static fromJson(js: JSON): Email {
    const e = new Email();
    // fill some attributes here
    if (js['attachment']) { e.attachment = Attachment.fromJson(js['attachment']); }
    return e;
  }
}
Run Code Online (Sandbox Code Playgroud)

文件:app/model/attachment.ts(部分代码)

import { Email } from './email';
export class Attachment {
  // some attributes
  public content: Email;

  public static fromJson(js: JSON): Attachment {
    const a = new Attachment();
    // fill some attributes here
    if (js['email']) { a.content = Email.fromJson(js['email']); }
    return a;
  }
}
Run Code Online (Sandbox Code Playgroud)

初始调用是: this.email = Email.fromJson(apiResponseForEmail);

这种情况导致在之后检测循环依赖项警告ng build | serve。如果这对您来说不是一个很好的例子,您可以想象Recipe食物类包含Ingredients数量和温度等属性,其中一个的结果Recipe是另一个食谱的成分。

如果这些类在一个文件中,则不会报告任何警告。但是,将所有内容放在一个大文件中对我来说并不是最好的解决方案(如果还有其他解决方案)。

这里是一个Stackblitz with Circular 依赖演示(但控制台没有警告,stackblitz 显然删除了警告,你需要下载这个代码并从 localhost 运行才能看到警告)。

我感兴趣的是是否可以将此类类(在示例中通过静态方法递归调用的代码中调用)放在单独的文件(由类命名的文件)中并避免循环依赖检测消息

arg*_*rgo 3

摆脱循环依赖的方法之一是引入index.ts

文件:index.ts

export { Attachment } from './attachment';
export { Email } from './email';
Run Code Online (Sandbox Code Playgroud)

文件:app/model/attachment.ts(部分代码)

import * as index_file from './index';
index_file.Attachment {
  ...
  content: index_file.Email;
}
Run Code Online (Sandbox Code Playgroud)

文件:app/model/email.ts(部分代码)

import * as index_file from './index';
index_file.Email {
  ...
  attachment?: index_file.Attachment;
}
Run Code Online (Sandbox Code Playgroud)

PS:请检查语法,我对语法没有信心