Angular-在继承中使用变量作为类型

时间:2018-07-17 23:08:02

标签: angular typescript inheritance

我有这个孩子班:

export class ChildService extends ParentService {
  protected model = ChildModel;
}

在父级中,我想将子级的模型用作http响应和诺言的类型!

getData(): Promise<this.model> { // doesn't work
  return this.http.get(this.url)
    .toPromise()
    .then(response => response as this.model) // doesn't work
    .catch(this.handleError);
}

有可能吗?

1 个答案:

答案 0 :(得分:1)

使用类型generics

export class ChildService extends ParentService<ChildModel> {
}

class ParentService<TType> {
   getData(): Promise<TType> {
      return this.http.get(this.url)
     .toPromise()
         .then(response => response as TType)
         .catch(this.handleError);
   }
}