首页 > 解决方案 > 访问在 ng-swagger-gen 中定义 api 参数的内部模块

问题描述

我对角度和类型脚本比较陌生。我正在为我的公司设计一个新的 spring/angular 框架,我正在利用 ng-swagger-gen 项目从 spring 控制器生成一个 angular 客户端。

我的问题是,当我为控制器定义多个参数时,ng-swagger-gen 创建一个包含它们的接口,我无法弄清楚如何从使用组件导入。

下面是生成的API

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpResponse, HttpHeaders } from '@angular/common/http';
import { BaseService as __BaseService } from '../base-service';
import { ApiConfiguration as __Configuration } from '../api-configuration';
import { StrictHttpResponse as __StrictHttpResponse } from '../strict-http-response';
import { Observable as __Observable } from 'rxjs';
import { map as __map, filter as __filter } from 'rxjs/operators';

import { VehicleBean } from '../models/vehicle-bean';
@Injectable({
  providedIn: 'root',
})
class ApiService extends __BaseService {
  static readonly helloPath = '/hello/sayhi';
  static readonly findVehiclePath = '/vehicle/find';
  static readonly listVehiclesPath = '/vehicle/list';

  constructor(
    config: __Configuration,
    http: HttpClient
  ) {
    super(config, http);
  }

  /**
   * @param toWhom undefined
   * @return successful operation
   */
  helloResponse(toWhom: string): __Observable<__StrictHttpResponse<string>> {
    let __params = this.newParams();
    let __headers = new HttpHeaders();
    let __body: any = null;
    if (toWhom != null) __params = __params.set('toWhom', toWhom.toString());
    let req = new HttpRequest<any>(
      'POST',
      this.rootUrl + `/hello/sayhi`,
      __body,
      {
        headers: __headers,
        params: __params,
        responseType: 'text'
      });

    return this.http.request<any>(req).pipe(
      __filter(_r => _r instanceof HttpResponse),
      __map((_r) => {
        return _r as __StrictHttpResponse<string>;
      })
    );
  }
  /**
   * @param toWhom undefined
   * @return successful operation
   */
  hello(toWhom: string): __Observable<string> {
    return this.helloResponse(toWhom).pipe(
      __map(_r => _r.body as string)
    );
  }

  /**
   * @return successful operation
   */
  findVehicleResponse(): __Observable<__StrictHttpResponse<VehicleBean>> {
    let __params = this.newParams();
    let __headers = new HttpHeaders();
    let __body: any = null;
    let req = new HttpRequest<any>(
      'GET',
      this.rootUrl + `/vehicle/find`,
      __body,
      {
        headers: __headers,
        params: __params,
        responseType: 'json'
      });

    return this.http.request<any>(req).pipe(
      __filter(_r => _r instanceof HttpResponse),
      __map((_r) => {
        return _r as __StrictHttpResponse<VehicleBean>;
      })
    );
  }
  /**
   * @return successful operation
   */
  findVehicle(): __Observable<VehicleBean> {
    return this.findVehicleResponse().pipe(
      __map(_r => _r.body as VehicleBean)
    );
  }

  /**
   * @param params The `ApiService.ListVehiclesParams` containing the following parameters:
   *
   * - `offset`:
   *
   * - `howMany`:
   *
   * @return successful operation
   */
  listVehiclesResponse(params: ApiService.ListVehiclesParams): __Observable<__StrictHttpResponse<Array<VehicleBean>>> {
    let __params = this.newParams();
    let __headers = new HttpHeaders();
    let __body: any = null;
    if (params.offset != null) __params = __params.set('offset', params.offset.toString());
    if (params.howMany != null) __params = __params.set('howMany', params.howMany.toString());
    let req = new HttpRequest<any>(
      'GET',
      this.rootUrl + `/vehicle/list`,
      __body,
      {
        headers: __headers,
        params: __params,
        responseType: 'json'
      });

    return this.http.request<any>(req).pipe(
      __filter(_r => _r instanceof HttpResponse),
      __map((_r) => {
        return _r as __StrictHttpResponse<Array<VehicleBean>>;
      })
    );
  }
  /**
   * @param params The `ApiService.ListVehiclesParams` containing the following parameters:
   *
   * - `offset`:
   *
   * - `howMany`:
   *
   * @return successful operation
   */
  listVehicles(params: ApiService.ListVehiclesParams): __Observable<Array<VehicleBean>> {
    return this.listVehiclesResponse(params).pipe(
      __map(_r => _r.body as Array<VehicleBean>)
    );
  }
}

module ApiService {

  /**
   * Parameters for listVehicles
   */
  export interface ListVehiclesParams {
    offset: number;
    howMany: number;
  }
}

export { ApiService }

我已将其打包到一个名为 poc-client-v2 的库中。我可以像这样导入和注入 ApiService 本身。

import {ApiService} from 'poc-client-v2';
import {ActivatedRoute, Router} from '@angular/router';
import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import {debounceTime} from 'rxjs/operators'; 
import {VehicleBean} from  'poc-client-v2/api/models/vehicle-bean';


@Component({
  selector: 'app-vehicle-list-example',
  templateUrl: './vehicle-list-example.component.html',
  styleUrls: ['./vehicle-list-example.component.css']
})


export class VehicleListExampleComponent implements OnInit {


  filterGroup: FormGroup;
  vehicles : VehicleBean[];

  constructor(private route: ActivatedRoute, private router: Router, private apiService: ApiService) {
    this.filterGroup = this.createFormGroup();

  }

  ngOnInit() {
     console.log('user list init: ');

    this.filterGroup.get('criteria').valueChanges.pipe( debounceTime(1000) ).subscribe(
      field=> { 
        console.log('criteria changed: ' + field);
       // Can't instantiate a new ListVehiclesParams here without the proper import
       // this.apiService.listVehicles(new ListVehiclesParams(0,20)).subscribe(data => {this.vehicles=data;})
      } 
    );
  }

   createFormGroup() {
    return new FormGroup({
      criteria: new FormControl('')
    });
  }
}

但我无法弄清楚如何在生成的 ApiService 底部定义的 ApiService 模块中导入 ListVehiclesParams 接口,因此我可以调用 listVehicles 方法。有人可以告诉我我缺少什么吗?

标签: angulartypescript

解决方案


要解决主要问题,为了访问ListVehiclesParams,您应该能够使用ApiService.ListVehiclesParams.

但是,如果你这样做了,你会注意到一个错误,因为你不能在 typescript 中以这种方式实例化接口。new ListVehiclesParams(0,20)是用于类的语法,但是您将接口实例化为普通对象(这是您最终在答案中所做的),例如:

const params: ApiService.ListVehicleParams = {
   offset: 10,
   howMany: 10,
};
this.apiService.listVehicles(params).subscribe(data => {this.vehicles=data;})

您可以在Typescript 的接口页面上找到有关此的更多信息

然而,尽管如此,typescript 的最大优势之一是它能够推断类型,并对这些推断类型强制执行安全性。在许多情况下,放弃类型并仅创建内联接口的实例是最简洁易读的解决方案,因此我认为您这样做的方式很棒。在您使用的解决方案中this.apiService.listVehicles({offset: 10, howMany: 10}),在幕后,打字稿确切地知道应该将什么类型传递给该方法。因此,如果您传递不符合接口定义的内容(例如{ofset: 10, howmany: 10}.


推荐阅读