2016-12-31 1 views
0

가져 오기 종속성이 있기 때문에 동일한 클래스가 동일한 .ts 파일에 있습니다.TypeScript의 순환 의존성을 리펙토링하여 별도의 TypeScript 파일을 사용할 수 있습니까?

첫 번째는 추상 GenericModel :

export abstract class GenericModel { 
    nodeClass: string; 
    id: string = "0"; 

    static fromJson(json: any): GenericModel { 
     if (json.nodeClass === "Entity") { 
      return EntityModel.fromJson(json); 
     } 
     else if(json.nodeClass === "User") { 
      return UserModel.fromJson(json); 
     } 
     return null; 
    } 
} 

다른 두 개의 클래스가 EntityModel를 (아래)하는 사람이 내가 수입의 순환 참조를 제거 할 수 있도록 내가 코드를 리팩토링 도움이 될 수 있다면 감사하겠습니다 및 UserModel :

export class EntityModel extends GenericModel { 
    nodeClass: string = "Entity"; 
    alias: string; 
    description: string; 

    constructor(public text: string, public id: string, public uuid: string, alias: string, public rand:string = "") { 
     //[...] 
    } 

    //instance methods 
    //[...] 

    public static fromJson(json: any): EntityModel { 
     var entity = new EntityModel(json.text, json.id, json.uuid, json.alias, json.rand); 
     entity.description = json.description; 

     if (json.types) { 
      for (let type of json.types) { 
       let objectifiedType: EntityModel = EntityModel.fromJson(type); 
       entity.types.push(objectifiedType); 
      } 
     } 
     if (json.innerEntities){ 
      for (let innerEntity of json.innerEntities) { 
       let objectifiedInnerEntity: EntityModel = EntityModel.fromJson(innerEntity); 
       entity.innerEntities.push(innerEntity); 
      } 
     } 
     return entity; 
    } 
} 

내가 여기서 뭐하는 거지 것은 nodeClass에 따라 정적 호출 fromJson()의 계층 구조를 사용하여 JSON의 직렬화이다.

그것은 GenericModel는 별도의 파일 인 경우가 별도의 파일에 있다면, 다른 2 명은 GenericModel를 가져올 필요가하면서 EntityModelUserModel 을 가져와야 것이 분명하다.

EntityModel --- has to import --> GenericModel

UserModel --- has to import --> GenericModel

는 지금뿐만 아니라 클래스는 별도의 .TS 파일에 무엇을 수행하도록 코드를 리팩토링 할 수있는 방법이 있는지 궁금

GenericModel --- has to import --> EntityModel, UserModel

.

감사합니다.

답변

2

여기에서 트릭은 순환 종속성을 자체 모듈로 분리하는 것입니다. 모든 fromJson 메서드를 하나의 새로운 모듈로 추출합니다. 그런 다음 을 ModelFactory과 같은 클래스로 변환합니다. 이제이 패턴이 팩토리 패턴과 유사하기 때문에.

export class ModelFactory { 
    // maybe add a constructor for some configuration data, maybe not 

    create(json: any) { 
    ... 
    } 
} 

지금, 나는 또한 당신이 anyjson 객체를 입력 볼 : 그래서, 최종 결과는 다음과 같을 것이다. 그 유형에 대해 최소한 몇 가지 속성을 알고있는 것처럼 보일 때 약간 넓게 보입니다. 나는이처럼 JSON 객체의 인터페이스를 만들려고 할 것 :

export interface ModelJson { // find a better name 
    text?: string; 
    id?: number; 
    uuid?: UUID; 
    alias?: string; 
    rand?: number; 
    ... 
} 

type UUID = number; 

는이 일을 더 typescripty 방법입니다.

+0

고마워요! 내가 제안한 공장과 같은 새로운 수업을 추가해야한다고 생각했습니다! 인터페이스/json의 팁 주셔서 감사 :) Btw'''유형 UUID = 번호;'''끝에? 새해 복 많이 받으세요! –

+1

그건 그냥 별칭입니다. 숫자가되는 UID와 같은 것이있을 때, 실제로는 기술적 인 세부 사항이며 자체적 인 의미론이있을 때, 종종 유형 별명을 사용합니다. 이렇게하면 UID 만 사용할 수 있고 실수로 바닐라 번호를 전달하지 않게됩니다. –

+0

나를 위해'''uuid'''는 문자열입니다! 여전히 할 수 있을까요?''type UUID = string;''? 감사합니다 –

관련 문제