【问题标题】:How do I reuse Angular 6 API services in a node script?如何在节点脚本中重用 Angular 6 API 服务?
【发布时间】:2019-03-20 04:01:06
【问题描述】:

我想在节点脚本中重用一些 Angular 6 API 服务,但在正确初始化所有内容时遇到了一些麻烦。

API 服务是使用 Swagger Codegen (-l typescript-angular) 生成的,例如:

@Injectable()
export class UserService {

    constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { 
      ... 
    }

}

这些服务在我的 Angular 6 应用程序中完美运行,我现在想在节点中使用它们来编写一些脚本。我知道 Swagger Codegen 也能够生成纯 Typescript 客户端,但仍希望重用现有的 Angular 服务以使代码库更加一致。

我现在面临的挑战是如何在没有依赖注入的情况下调用这个构造函数。

如果没有依赖注入,似乎很难获得有效的HttpClient 对象。在 AngularJS 中,我曾经为此依赖 Axios,但该库似乎不再提供与 HttpClient 相同的接口(仍然承诺而不是 Angular 6 中较新的 observables)。

在我看来有两种选择:

  1. 不知何故得到一个HttpClient 对象 -> 无法让它工作。
  2. 注入另一个公开相同接口的 HTTP 客户端对象 -> 似乎找不到。

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

干杯,

M.

【问题讨论】:

  • 在任何情况下,您都不受限于 Angular 中的 HttpClient。如果您认为 Axios 可以简化任务,您可以在自己的代码中使用它。当然,如果您生成的样板文件已经使用了 HttpClient,这将不起作用。

标签: node.js angular typescript


【解决方案1】:

HttpClient 不应该被手动实例化,这不是一个简单的过程,因为它有很多依赖项。 Angular 注入器完成了依赖注入的所有工作,应该用于获取实例。

this answer 所示,可以通过设置模块并引导它来获取 Angular 提供程序 (HttpClient) 的实例。

应该对UserService 使用非常相似的方法。这是简化但可行的示例:

import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import {Injector, Injectable, NgModule } from '@angular/core'
import {HttpClient, HttpClientModule} from '@angular/common/http'
import {ServerModule, platformDynamicServer} from '@angular/platform-server';

@Injectable()
export class UserService {
  constructor(protected httpClient: HttpClient) { 
    httpClient.get('https://google.com/').subscribe(console.log, console.error);
  }
}

@NgModule({
  imports: [ServerModule, HttpClientModule],
  providers: [UserService]
})
export class AppModule {
  ngDoBootstrap() {}
}

(async () => {
    const platform = platformDynamicServer();
    const appModule = await platform.bootstrapModule(AppModule);
    const userService = appModule.injector.get(UserService);
})()
.catch(console.error);

它需要兼容的 TypeScript 配置,例如:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

【讨论】:

  • 太棒了,找这个很久了:D 谢谢!
  • 很高兴它有帮助。
猜你喜欢
  • 2019-11-03
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2019-01-09
  • 2020-11-03
  • 2014-08-03
相关资源
最近更新 更多