【问题标题】:Angular4 and Swagger ClientAngular4 和 Swagger 客户端
【发布时间】:2018-04-13 23:16:00
【问题描述】:

也许有人可以帮忙。我尝试使用组件中的默认服务与 REST API 通信到后端 python-Server。我尝试使用 swagger-codegen 生成的 ng2 客户端。 Python服务器也是swagger生成的。服务器正在工作,

import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';

import { InlineResponseDefault } from '../model/inlineResponseDefault';

import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { CustomQueryEncoderHelper } from '../encoder';


@Injectable()
export class DefaultService {

    protected basePath = 'http://127.0.0.1:8080/v1';
    public defaultHeaders = new Headers();
    public configuration = new Configuration();

    constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
        if (basePath) {
            this.basePath = basePath;
        }
        if (configuration) {
            this.configuration = configuration;
            this.basePath = basePath || configuration.basePath || this.basePath;
        }
    }

    /**
     * @param consumes string[] mime-types
     * @return true: consumes contains 'multipart/form-data', false: otherwise
     */
    private canConsumeForm(consumes: string[]): boolean {
        const form = 'multipart/form-data';
        for (let consume of consumes) {
            if (form === consume) {
                return true;
            }
        }
        return false;
    }


    public isJsonMime(mime: string): boolean {
        const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
        return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
    }

    /**
     * Abort the programm in the project identified by UUID
     * @param UUID The UUID
     */
    public abortProject(UUID: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
        return this.abortProjectWithHttpInfo(UUID, extraHttpRequestParams)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json() || {};
                }
            });
    }

    /**
     * delete a single file at a specified path
     * @param UUID The UUID
     * @param path The path where to upload.
     */
    public deleteFile(UUID: string, path: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
        return this.deleteFileWithHttpInfo(UUID, path, extraHttpRequestParams)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json() || {};
                }
            });
    }

    /**
     * Testing the connection
     */
    public ping(extraHttpRequestParams?: RequestOptionsArgs): Observable<string> {
        return this.pingWithHttpInfo(extraHttpRequestParams)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json() || {};
                }
            });
    }

我的 app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DefaultService } from './rest/api/default.service';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [DefaultService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

我尝试在我的构造函数中注入 default.service,然后浏览器给出消息 ERROR NO PROVIDER FOR HTTP Injection 错误..... 我完全是 ng 和 ts 的新手 :-( 。之后我为控制台定义了一个函数 getPing 记录服务器的答案。

import { Component, OnInit } from '@angular/core';
import { InlineResponseDefault } from '../app/rest';
import { HttpClient, } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Response } from '@angular/http';
import { DefaultService } from './rest/api/default.service';
import { HttpClientModule } from '@angular/common/http';



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


export class AppComponent {
  title = 'app';


  constructor(private defaultService: DefaultService, public http: HttpClient) {

  }

  getPing() {
    console.log(this.defaultService.ping);
      }

}

【问题讨论】:

    标签: angular swagger-2.0 angular-httpclient


    【解决方案1】:

    Http 在一个地方,HttpClient 在另一个地方。我强烈推荐reading the documentation。我假设您打算使用HttpClient,但如果您想改用Http,请参考this other documentation

    default.service.ts 中更新您的构造函数以使用 HttpClient:

    constructor(protected http: HttpClient, ... other params ...)
    

    app.component.ts 中:

    • 去掉HttpClient构造函数参数:

      constructor(private defaultService: DefaultService) {}
      
    • 更新您的 getPing() 方法以在默认服务上实际调用 ping() 方法:

      console.log(this.defaultService.ping()); 
      

      如果没有(),它会返回一个函数引用而不是调用该函数。

    • 删除 HttpClientModule 的导入。您只需要在 app.module.ts 文件中使用它。

    你的 app.module.ts 没问题。

    实际上,我什至看不到该默认服务将如何编译,因为它似乎正在调用一大堆方法,只是......不存在。

    正如我之前提到的,这是给HttpClient。如果你想使用Http,你需要使用HttpModule。请参阅我上面链接的文档,但建议您使用HttpClient

    【讨论】:

    • 谢谢你,我已经解决了。你说一大堆方法都不存在......哪些方法?我以为我可以从我的招摇客户端调用该函数,然后他 ping 服务器?你能推荐一个我可以阅读更多关于 angular4 和客户端实现的来源吗?
    • @PaddyS 这样的未定义方法:this.abortProjectWithHttpInfo(...)。 “this”关键字表示这是一个类方法,但DefaultService 没有声明名为abortProjectWithHttpInfo 的方法。如果这实际上是您的 api 中的一个方法,您必须调用类似 this.http.post("http://example.com/api/abortProjectWithHttpInfo",...) 的方法。
    • 《冰雪奇缘》感谢您的帮助。我在下面的评论中发布了整个 default.service 文件以及一些文本。
    • @PaddyS 如果您有其他问题,您应该创建一个新问题。 StackOverflow 遵循问答模型,而不是多回复模型,因此我们希望每个主题保留一个概念(或问题/答案)。
    【解决方案2】:

    问题在于,在 app.module.ts 中,您从 @angular/common/http 导入 HttpClientModule,而在您的服务中,您正试图从 @ 注入 HttpClient角度/http。与 Http 客户端版本不同,@angular/common/http 是最新的。

    将您的服务更改为:

    import { HttpClient } from '@angular/common/http';
    //
    @Injectable()
    export class DefaultService {
      constructor(protected http: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
    

    【讨论】:

      【解决方案3】:

      @Roddy of the Frozen 这就是我的全部 default.service.ts。你说如果我有这种方法,我需要调用this.http.post("http://example.com/api/abortProjectWithHttpI‌​nfo",...),但我认为如果我 ping 服务器,我可以从我的 default.service 使用 ping。我只是意识到我在浏览器中的角度应用程序是空的。 HTML 将不会显示......这很令人沮丧。

      import { Inject, Injectable, Optional } from '@angular/core';
      import { Http, Headers, URLSearchParams } from '@angular/http';
      import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
      import { Response, ResponseContentType } from '@angular/http';
      import { HttpClient } from '@angular/common/http';
      
      import { Observable } from 'rxjs/Observable';
      import '../rxjs-operators';
      
      import { InlineResponseDefault } from '../model/inlineResponseDefault';
      
      import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
      import { Configuration } from '../configuration';
      import { CustomQueryEncoderHelper } from '../encoder';
      
      
      @Injectable()
      export class DefaultService {
      
          protected basePath = 'http://127.0.0.1:8080/v1';
          public defaultHeaders = new Headers();
          public configuration = new Configuration();
      
          constructor(protected http: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
              if (basePath) {
                  this.basePath = basePath;
              }
              if (configuration) {
                  this.configuration = configuration;
                  this.basePath = basePath || configuration.basePath || this.basePath;
              }
          }
      
          /**
           * @param consumes string[] mime-types
           * @return true: consumes contains 'multipart/form-data', false: otherwise
           */
          private canConsumeForm(consumes: string[]): boolean {
              const form = 'multipart/form-data';
              for (let consume of consumes) {
                  if (form === consume) {
                      return true;
                  }
              }
              return false;
          }
      
      
          public isJsonMime(mime: string): boolean {
              const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
              return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
          }
      
          /**
           * Abort the programm in the project identified by UUID
           * @param UUID The UUID
           */
          public abortProject(UUID: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
              return this.abortProjectWithHttpInfo(UUID, extraHttpRequestParams)
                  .map((response: Response) => {
                      if (response.status === 204) {
                          return undefined;
                      } else {
                          return response.json() || {};
                      }
                  });
          }
      
          /**
           * delete a single file at a specified path
           * @param UUID The UUID
           * @param path The path where to upload.
           */
          public deleteFile(UUID: string, path: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
              return this.deleteFileWithHttpInfo(UUID, path, extraHttpRequestParams)
                  .map((response: Response) => {
                      if (response.status === 204) {
                          return undefined;
                      } else {
                          return response.json() || {};
                      }
                  });
          }
      
          /**
           * Testing the connection
           */
          public ping(extraHttpRequestParams?: RequestOptionsArgs): Observable<string> {
              return this.pingWithHttpInfo(extraHttpRequestParams)
                  .map((response: Response) => {
                      if (response.status === 204) {
                          return undefined;
                      } else {
                          return response.json() || {};
                      }
                  });
          }
      
          /**
           * Run the programm in the project identified by UUID
           * @param UUID The UUID
           */
          public runProject(UUID: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
              return this.runProjectWithHttpInfo(UUID, extraHttpRequestParams)
                  .map((response: Response) => {
                      if (response.status === 204) {
                          return undefined;
                      } else {
                          return response.json() || {};
                      }
                  });
          }
      
          /**
           * Send a single file to the server
           * @param UUID The UUID
           * @param path The path where to upload.
           * @param file The single file to upload.
           */
          public sendFile(UUID: string, path: string, file: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable<{}> {
              return this.sendFileWithHttpInfo(UUID, path, file, extraHttpRequestParams)
                  .map((response: Response) => {
                      if (response.status === 204) {
                          return undefined;
                      } else {
                          return response.json() || {};
                      }
                  });
          }
      
      
          /**
           * 
           * Abort the programm in the project identified by UUID
           * @param UUID The UUID
           */
          public abortProjectWithHttpInfo(UUID: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<Response> {
              if (UUID === null || UUID === undefined) {
                  throw new Error('Required parameter UUID was null or undefined when calling abortProject.');
              }
      
              let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
      
              // to determine the Content-Type header
              let consumes: string[] = [
                  'application/x-www-form-urlencoded'
              ];
              let canConsumeForm = this.canConsumeForm(consumes);
              let useForm = false;
              let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
                set(param: string, value: any): void;
              };
              if (UUID !== undefined) {
                  formParams.set('UUID', <any>UUID);
              }
      
              let requestOptions: RequestOptionsArgs = new RequestOptions({
                  method: RequestMethod.Post,
                  headers: headers,
                  body: formParams.toString(),
                  withCredentials:this.configuration.withCredentials
              });
              // https://github.com/swagger-api/swagger-codegen/issues/4037
              if (extraHttpRequestParams) {
                  requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
              }
      
              return this.http.request(`${this.basePath}/abort`, requestOptions);
          }
      
          /**
           * 
           * delete a single file at a specified path
           * @param UUID The UUID
           * @param path The path where to upload.
           */
          public deleteFileWithHttpInfo(UUID: string, path: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<Response> {
              if (UUID === null || UUID === undefined) {
                  throw new Error('Required parameter UUID was null or undefined when calling deleteFile.');
              }
              if (path === null || path === undefined) {
                  throw new Error('Required parameter path was null or undefined when calling deleteFile.');
              }
      
              let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
      
              // to determine the Content-Type header
              let consumes: string[] = [
                  'multipart/form-data'
              ];
              let canConsumeForm = this.canConsumeForm(consumes);
              let useForm = false;
              let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
                set(param: string, value: any): void;
              };
              if (UUID !== undefined) {
                  formParams.set('UUID', <any>UUID);
              }
              if (path !== undefined) {
                  formParams.set('path', <any>path);
              }
      
              let requestOptions: RequestOptionsArgs = new RequestOptions({
                  method: RequestMethod.Delete,
                  headers: headers,
                  body: formParams.toString(),
                  withCredentials:this.configuration.withCredentials
              });
              // https://github.com/swagger-api/swagger-codegen/issues/4037
              if (extraHttpRequestParams) {
                  requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
              }
      
              return this.http.request(`${this.basePath}/delete`, requestOptions);
          }
      
          /**
           * 
           * Testing the connection
           */
          public pingWithHttpInfo(extraHttpRequestParams?: RequestOptionsArgs): Observable<Response> {
      
              let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
      
              let requestOptions: RequestOptionsArgs = new RequestOptions({
                  method: RequestMethod.Get,
                  headers: headers,
                  withCredentials:this.configuration.withCredentials
              });
              // https://github.com/swagger-api/swagger-codegen/issues/4037
              if (extraHttpRequestParams) {
                  requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
              }
      
              return this.http.request(`${this.basePath}/ping`, requestOptions);
          }
      
          /**
           * 
           * Run the programm in the project identified by UUID
           * @param UUID The UUID
           */
          public runProjectWithHttpInfo(UUID: string, extraHttpRequestParams?: RequestOptionsArgs): Observable<Response> {
              if (UUID === null || UUID === undefined) {
                  throw new Error('Required parameter UUID was null or undefined when calling runProject.');
              }
      
              let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
      
              // to determine the Content-Type header
              let consumes: string[] = [
                  'application/x-www-form-urlencoded'
              ];
              let canConsumeForm = this.canConsumeForm(consumes);
              let useForm = false;
              let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
                set(param: string, value: any): void;
              };
              if (UUID !== undefined) {
                  formParams.set('UUID', <any>UUID);
              }
      
              let requestOptions: RequestOptionsArgs = new RequestOptions({
                  method: RequestMethod.Post,
                  headers: headers,
                  body: formParams.toString(),
                  withCredentials:this.configuration.withCredentials
              });
              // https://github.com/swagger-api/swagger-codegen/issues/4037
              if (extraHttpRequestParams) {
                  requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
              }
      
              return this.http.request(`${this.basePath}/run`, requestOptions);
          }
      
          /**
           * 
           * Send a single file to the server
           * @param UUID The UUID
           * @param path The path where to upload.
           * @param file The single file to upload.
           */
          public sendFileWithHttpInfo(UUID: string, path: string, file: Blob, extraHttpRequestParams?: RequestOptionsArgs): Observable<Response> {
              if (UUID === null || UUID === undefined) {
                  throw new Error('Required parameter UUID was null or undefined when calling sendFile.');
              }
              if (path === null || path === undefined) {
                  throw new Error('Required parameter path was null or undefined when calling sendFile.');
              }
              if (file === null || file === undefined) {
                  throw new Error('Required parameter file was null or undefined when calling sendFile.');
              }
      
              let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
      
              // to determine the Content-Type header
              let consumes: string[] = [
                  'multipart/form-data'
              ];
              let canConsumeForm = this.canConsumeForm(consumes);
              let useForm = false;
              useForm = canConsumeForm;
              let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
                set(param: string, value: any): void;
              };
              if (UUID !== undefined) {
                  formParams.set('UUID', <any>UUID);
              }
              if (path !== undefined) {
                  formParams.set('path', <any>path);
              }
              if (file !== undefined) {
                  formParams.set('file', <any>file);
              }
      
              let requestOptions: RequestOptionsArgs = new RequestOptions({
                  method: RequestMethod.Post,
                  headers: headers,
                  body: formParams.toString(),
                  withCredentials:this.configuration.withCredentials
              });
              // https://github.com/swagger-api/swagger-codegen/issues/4037
              if (extraHttpRequestParams) {
                  requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
              }
      
              return this.http.request(`${this.basePath}/files`, requestOptions);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-05
        • 1970-01-01
        • 2017-07-15
        • 2018-01-24
        • 1970-01-01
        • 2017-08-06
        相关资源
        最近更新 更多