【问题标题】:Accessing inner modules defining api parameters in ng-swagger-gen访问在 ng-swagger-gen 中定义 api 参数的内部模块
【发布时间】:2020-08-04 14:41:25
【问题描述】:

我对角度和类型脚本比较陌生。我正在为我的公司设计一个新的 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 方法。有人可以告诉我我缺少什么吗?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    答案是根本不导入它。而只是用正确的参数名称实现一个 json 格式的对象。

    this.apiService.listVehicles({offset:10,howMany:10}).subscribe(data =&gt; {this.vehicles=data;})

    【讨论】:

    • 这是一个很好的解决方案,但我已经提交了一个答案,希望能更彻底地解释这种情况
    【解决方案2】:

    要解决主要问题,要访问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's page on interfaces找到更多信息

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2010-09-16
      • 2016-03-09
      • 2021-02-18
      • 1970-01-01
      相关资源
      最近更新 更多