无法将服务注入 Angular Provider UseFactory

S. *_*nke 3 dependency-injection angular

一些背景信息:我使用 Nswag 和 ASP Net Core 创建了一个生成的 API 客户端。要设置 api 客户端的基本 url,请使用以下代码:

export const API_BASE_URL = new InjectionToken<string>(
  "API_BASE_URL"
);

@Injectable({
  providedIn: "root",
})
export class ApiClient {
  // Omitting code for brevity

  constructor(
    @Inject(HttpClient) http: HttpClient,
    @Optional() @Inject(API_BASE_URL) baseUrl?: string
  ) {
    this.http = http;
    this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "";
  }
  
  // Etc..
}
Run Code Online (Sandbox Code Playgroud)

现在我需要注册它,API_BASE_URL以便可以将其注入到NotificatiesClient. 我在 app.module.ts 中执行了以下操作:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, HttpClientModule],
  providers: [
    {
      provide: NOTIFICATIESERVICE_API_BASE_URL,
      useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

假设ServiceToInject有这样的服务:

// Note 1: I tried with providedIn: 'root', but that did not make a difference.
// Note 2: This one is stored in src/app/core/services/ServiceToInject.service.ts
@Injectable()
export class ServiceToInject{
  // Service here
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用以下代码API_BASE_URL在我的中注册提供程序时:app.module.ts

providers: [
  {
    provide: API_BASE_URL,
    useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
  },
],
Run Code Online (Sandbox Code Playgroud)

我收到一个Can't resolve all parameters for useFactory错误。

有人知道如何解决这个问题吗?

S. *_*nke 5

就我而言,答案非常简单!

提供程序代码需要一个deps使用我在 my 中使用的依赖项类型调用的属性useFactory,如下所示:

{
  provide: NOTIFICATIESERVICE_API_BASE_URL,
  deps: [AppConfigService],
  useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
},
Run Code Online (Sandbox Code Playgroud)

我希望它能帮助你们!