一个老问题,大部分是正确的,但不是很有效的答案。这是我的建议:
创建一个包含 init() 方法和静态转换方法(用于单个对象和数组)的基类。静态方法可以在任何地方;带有基类和 init() 的版本允许以后轻松扩展。
export class ContentItem {
// parameters: doc - plain JS object, proto - class we want to cast to (subclass of ContentItem)
static castAs<T extends ContentItem>(doc: T, proto: typeof ContentItem): T {
// if we already have the correct class skip the cast
if (doc instanceof proto) { return doc; }
// create a new object (create), and copy over all properties (assign)
const d: T = Object.create(proto.prototype);
Object.assign(d, doc);
// reason to extend the base class - we want to be able to call init() after cast
d.init();
return d;
}
// another method casts an array
static castAllAs<T extends ContentItem>(docs: T[], proto: typeof ContentItem): T[] {
return docs.map(d => ContentItem.castAs(d, proto));
}
init() { }
}
@Adam111p 帖子中提到了类似的机制(使用 assign())。只是另一种(更完整)的方法。 @Timothy Perez 对 assign() 持批评态度,但恕我直言,这里完全合适。
实现一个派生(真正的)类:
import { ContentItem } from './content-item';
export class SubjectArea extends ContentItem {
id: number;
title: string;
areas: SubjectArea[]; // contains embedded objects
depth: number;
// method will be unavailable unless we use cast
lead(): string {
return '. '.repeat(this.depth);
}
// in case we have embedded objects, call cast on them here
init() {
if (this.areas) {
this.areas = ContentItem.castAllAs(this.areas, SubjectArea);
}
}
}
现在我们可以转换从服务中检索到的对象:
const area = ContentItem.castAs<SubjectArea>(docFromREST, SubjectArea);
SubjectArea 对象的所有层次结构都将具有正确的类。
一个用例/示例;创建一个 Angular 服务(再次抽象基类):
export abstract class BaseService<T extends ContentItem> {
BASE_URL = 'http://host:port/';
protected abstract http: Http;
abstract path: string;
abstract subClass: typeof ContentItem;
cast(source: T): T {
return ContentItem.castAs(source, this.subClass);
}
castAll(source: T[]): T[] {
return ContentItem.castAllAs(source, this.subClass);
}
constructor() { }
get(): Promise<T[]> {
const value = this.http.get(`${this.BASE_URL}${this.path}`)
.toPromise()
.then(response => {
const items: T[] = this.castAll(response.json());
return items;
});
return value;
}
}
用法变得非常简单;创建一个区域服务:
@Injectable()
export class SubjectAreaService extends BaseService<SubjectArea> {
path = 'area';
subClass = SubjectArea;
constructor(protected http: Http) { super(); }
}
服务的
get() 方法将返回已转换为 SubjectArea 对象(整个层次结构)的数组的 Promise
现在说,我们有另一个类:
export class OtherItem extends ContentItem {...}
创建一个检索数据并转换为正确类的服务非常简单:
@Injectable()
export class OtherItemService extends BaseService<OtherItem> {
path = 'other';
subClass = OtherItem;
constructor(protected http: Http) { super(); }
}