Angular 我应该在什么时候使用抽象?

Angular 我应该在什么时候使用抽象?,angular,typescript,Angular,Typescript,在我的过去,我见过一些JavaEE、.Net和其他企业应用程序架构。其中每一个都至少有一个抽象的上层类,用于概括例如服务层:AbstractService 但说到角度,我从来没有见过这样的东西。即使它有一些标准化的服务/api层 我想知道这是否会被认为是typescript中的一种不好的做法,因为它下面只是JavaScript。或者仅仅是因为没有深入的教程或指南,而现实世界中的企业应用程序确实会使用这种抽象?我有点困惑。Angular中的抽象类有一些常见的用例,最突出的是用作依赖注入标记的抽象类

在我的过去,我见过一些JavaEE、.Net和其他企业应用程序架构。其中每一个都至少有一个抽象的上层类,用于概括例如服务层:AbstractService

但说到角度,我从来没有见过这样的东西。即使它有一些标准化的服务/api层


我想知道这是否会被认为是typescript中的一种不好的做法,因为它下面只是JavaScript。或者仅仅是因为没有深入的教程或指南,而现实世界中的企业应用程序确实会使用这种抽象?我有点困惑。

Angular中的
抽象类有一些常见的用例,最突出的是用作依赖注入标记的抽象类

依赖注入令牌(实现)

这种方法对于单元测试非常有用。您可以在
TestBed.configureTestingModule()或
TestBed.overrideProvider()中重写

服务基类(扩展)

我没有在教程或演示中看到过这么多,但在现实世界的应用程序中使用过

export abstract class AbstractBaseService {
   // extending classes forced to implement these properties/functions
   protected abstract serviceID: string;
   protected abstract provideInitialState(): IState;

   protected formatResponse(response: IAccountResponse): IFormattedResponse {
       // logic accessible to sub-classes
       // override if necessary
   }
}

export class AccountService extends AbstractBaseService {
   // implement abstract properties and functions
   // override protected/private properties and functions if needs be
}
注释

export abstract class AbstractEventService {
  dispatchEvent(event: any): void;
  listen(event: any): Observable<any>;
}

// Use the abstract class as interfaces
export class EventService implements AbstractEventService {
   // The compiler will force you to implement dispatchEvent() and listen()
}


您会注意到我提到了覆盖受保护/私有属性和函数-这是TypeScript的一个限制,因为它允许重写任何抽象类属性和函数

第一个抽象类来自Java SE而不是EE。关于Java EE工具,如
spring
有一些比
依赖注入
等抽象类更好的发明。我与Angular合作了2年,可能用过两次,而且它也特别适用于我开发的一个没有它也可以做的案例。Angular本身不要求在我的日常工作中使用任何Abstract类。我已经为Angular服务和组件实现了企业级Angular,使用基本TypeScript类。他有自己的依赖项注入工具,他称之为服务no,我同意你的评论,没有使用扩展基类的教程和演示。特别是在服务方面。您可以使用基本服务减少大量CRUD开销,并且可以包装标准http请求,这样您就可以在一个位置以特定于应用程序的方式轻松处理请求错误,而不是在单独的服务中反复编写相同的“出错”代码。@Rob-我们对API服务也这样做。我猜TypeScript的OOD方面通常是内部的——在博客领域没有太多的兴趣:——)@Rob这正是我写这篇文章时考虑的。很高兴听到有人用crud服务做到这一点!
export abstract class AbstractBaseService {
   // extending classes forced to implement these properties/functions
   protected abstract serviceID: string;
   protected abstract provideInitialState(): IState;

   protected formatResponse(response: IAccountResponse): IFormattedResponse {
       // logic accessible to sub-classes
       // override if necessary
   }
}

export class AccountService extends AbstractBaseService {
   // implement abstract properties and functions
   // override protected/private properties and functions if needs be
}