【发布时间】:2019-10-13 02:20:15
【问题描述】:
我正在尝试为从服务器获取响应的代理服务创建一个通用类。当我留下来实现这个类时,我遇到了一个问题,从泛型类中调用一个方法。如何从泛型类型声明的 Js(item) 中调用静态方法?
export class CollectionResult<T> implements ICollectionResult<T> {
items: Array<T>;
constructor(data?: T) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
Object.assign(this, data);
this.items = [];
for (let item of data.items) {
this.items.push(T//NOTE: Error here//.fromJS(item));
}
}
}
fromJS(data: any): CollectionResult<T> {
let result = new CollectionResult<T>();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
Object.assign(data, this);
if (this.items && this.items.constructor === Array) {
data["items"] = [];
for (let item of this.items) {
data["items"].push(item);
}
}
return data;
}
}
export interface ICollectionResult<T> {
items: Array<T>;
}
// CollectionResult 中传入的泛型类
export class ProgramDto implements
IProgramDto {
year: number;
month: number;
accounts: number;
constructor(data?: ProgramDto) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
Object.assign(this, data);
}
}
static fromJS(data: any): ProgramDto {
let result = new ProgramDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
Object.assign(data, this);
return data;
}
}
export interface IProgramDto {
year: number;
month: number;
accounts: number;
}
//在代理方法中的使用
Get(): Observable<CollectionResult<ProgramDto >> {
let url = `${this.baseUrl}/Api/Controller/Method`;
url = url.replace(/[?&]$/, "");
let options = this.getOptions();
return this.sendRequestWithResponse(url, options, CollectionResult<ProgramDto>.fromJS, new CollectionResult<ProgramDto>());
}
【问题讨论】:
-
或者使用
this.fromJS? -
我的意思是来自泛型类 T 的静态方法,而不是来自当前的
标签: angular typescript generics server proxy