2017-09-08 1 views
0

각도를 사용하여 & 유형 스크립트를 사용하여 일종의 유형 안전성을 보장하기 위해 제네릭과 모든 컴파일 - 장점을 사용할 수 있습니다. 그러나 예를 들어 HTTP-Service를 사용하는 경우 특정 객체는 얻지 못하고 JSON을 파싱합니다. 우리는 단지 JSON을 얻을 수 있기 때문에TypeScript : 복잡한 객체를 재귀 적으로 생성

public get<T>(relativeUrl: string): Promise<T> { 
    const completeUrlPromise = this.createCompleteUrl(relativeUrl); 
    const requestOptions = this.createRequestOptions(ContentType.ApplicationJson, true); 
    return completeUrlPromise.then(completeUrl => { 
     return this.processResponse<T>(this.http.get(completeUrl, requestOptions)); 
    }); 
    } 

    private processResponse<T>(response: Observable<Response>): Promise<T> { 
    const mappedResult = response.map(this.extractData); 

    const result = mappedResult.toPromise(); 
    return result; 
    } 

    private extractData(res: Response): any { 
    let body; 
    if (!Array.isArray(res)) { 
     if (res.text()) { 
     body = res.json(); 
     } 
    } else { 
     body = res; 
    } 

    if (!JsObjUtilities.isNullOrUndefined(body)) { 
     return body; 
    } 

    return {}; 
    } 

궁극적으로, 일반 유형, 이런 식으로 쓸모가 예를 들어, 우리는 몇 가지 일반적인 방법이 있다고하고있다. 제네릭 객체에 JSON에없는 메서드 또는 속성이 있으면 손실됩니다. 이처럼 보이는

private processResponse<T>(response: Observable<Response>, ctor: IParameterlessConstructor<T> | null = null): Promise<T> { 
    let mappedResult = response.map(this.extractData); 

    if (ctor) { 
     mappedResult = mappedResult.map(f => { 
     const newObj = JsObjFactory.create(f, ctor); 
     return newObj; 
     }); 
    } 

    const result = mappedResult.toPromise(); 
    return result; 
    } 

그리고 JsObjFactory : 는이를 방지하기 위해, 우리는 진정으로 객체 생성하기 위해 생성자 함수를 통과 할 수있는 가능성을 추가

export class JsObjFactory { 
    public static create<T>(source: any, ctorFn: IParameterlessConstructor<T>): T { 
    const result = new ctorFn(); 
    this.mapDefinedProperties(source, result); 

    return result; 
    } 

    private static mapDefinedProperties<T>(source: Object, target: T): void { 
    const properties = Object.getOwnPropertyNames(target); 

    properties.forEach(propKey => { 
     if (source.hasOwnProperty(propKey)) { 
     target[propKey] = source[propKey]; 
     } 
    }); 
    } 
} 

이 얕은 객체에 대해 잘 작동을하지만, 속성이 또한 생성자가있는 복합 유형 인 경우 작동하지 않습니다. 런타임에 타입이 없으므로, 현재 내가 가진 kindahow 속성을 분석하고 클래스가 있는지 확인한 다음 생성하는 것이 가장 좋습니다. 그러나 이것은 매우 오류가 발생하기 쉽고 성가신 것 같습니다.

저는 항상이 문제가있는 유일한 사람이 아니며 해결책이 있습니까, 아니면 TypeScript/JavaScript 기능이 아닌지 잘 모르겠지만 여기에서 도움이 될 것 같습니까?

+0

가능한 복제본 [JSON 객체로 typescript 객체를 초기화하는 방법] (https://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-a- json-object) (거기에 좋은 답변이 있습니다) – jcalz

답변

0

개인적으로 이렇게하지는 않지만 원하는 내용 일 수 있습니다.

예 :

Customer.ts

export interface ICustomer { 
    Id: number; 
    Name: string; 
    Orders: IOrder[]; 
    ... 
} 

export class Customer implements ICustomer { 
    public Id: number; 
    public Name: string; 
    public Orders: IOrder[]; 

    constructor(customer: Partial<ICustomer>) { 
     this.Id = customer.Id || 0; 
     this.Name = customer.Name || ''; 
     this.Orders = []; 
     customer.Orders.forEach((order: IOrder) => this.Orders.push(new Order(order))); 
    } 

    //some functions 
} 

Order.ts

export interface IOrder { 
    Id: number; 
    Weight: number; 
    Shipmentdate: string; 
} 

export class Order implements IOrder { 
    public Id: number; 
    public Weight: number; 
    public Shipmentdate: string; 

    constructor(order: Partial<IOrder>) { 
     this.Id = order.Id || 0; 
     this.Weight = order.Weight || 0; 
     this.Shipmentdate = order.Shipmentdate || ''; 
    } 

    //some functions 
} 

이것은 Object이 알려진 인스턴스에 대한 책임 (이 경우 Customer에) 할 것 복잡한 유형을 전달합니다. 그리고 Order은 다시 인스턴스화하는 복잡한 유형을 가질 수 있습니다.

+0

감사합니다. 질문은 JSON에서 이름을 제외하고 무엇을 만들지 만 어떻게 알 수 있습니까? –

+0

@ MatthiasMüller 수업 자체는 알고 있나요? 아니면 내가 너를 오해하고 있니? – Arg0n

관련 문제