我有以下类型记录服务代码,我希望通过一个新的角度模块公开。
通用服务
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { AuthHeaders } from "./auth.headers";
export abstract class BaseHttpService<T> {
  baseAPIUrl: string;
  serviceAPISegment: string;
  private requestOptions = {
    headers: this.authHeaders.getHeaders()
  };
  constructor(
    private httpClient: HttpClient,
    private authHeaders: AuthHeaders
  ) {}
  get<T>(): Observable<T[]> {
    return this.httpClient.get<T[]>(
      `${this.baseAPIUrl}\\${this.serviceAPISegment}`,
      this.requestOptions
    );
  }
}模块声明
import { NgModule } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { BaseHttpService } from "./asyncServices/http/base.http.service";
@NgModule({
  imports: [
    HttpClientModule
  ],
  declarations: [
    BaseHttpService
  ]
})
export class SharedModule {}我得到了BaseHttpService中的错误,如下所示
src/app/shared/shared.module.ts(11,5)中的错误:错误TS2322:键入‘BaseHttpService’类型不能分配到键入'any[] \\类型‘。键入‘Type not’不能分配到键入' type‘。不能将抽象构造函数类型分配给非抽象构造函数类型。
我尝试了以下BaseHttpService BaseHttpService<>
但都不起作用。请建议在本模块中注册服务的合适方式。
发布于 2018-11-26 10:52:18
根据您想要使用的模块,您必须在导入{ provide ..., useClass ...}的模块中使用一个SharedModule构造。因此,如果您想在某种模块中使用它:
@NgModule({
  imports: [
    SharedModule
  ],
  providers: [
    {  provide: BaseHttpService<any>, useClass: SomeKindHttpService<any> }
  ]
})
export class SomeKindModule {}并让您的服务扩展BaseHttpService
export class SomeKindHttpService<T> extends BaseHttpService<T> {
  constructor(
    httpClient: HttpClient,
    authHeaders: AuthHeaders
   ) {
     super(httpClient, authHeaders);
   }
}发布于 2018-11-26 10:52:21
这里有两个问题。服务不是声明,而是提供的。它应该在模块实例化的“提供”属性中。另外,您如何期望角度DI系统知道如何提供抽象类?它需要知道T是什么,它没有办法弄清楚这一点。
发布于 2018-11-26 10:52:37
服务是抽象的,因此不能实例化。您应该将其非抽象化,或者让其他服务扩展它。
此外,应将服务添加到声明属性中,但应添加属性"providers“。
https://stackoverflow.com/questions/53479399
复制相似问题