Search code examples
angularswagger-2.0angular-httpclient

Angular4 and Swagger Client


maybe someone can help. I try to use the default service in my component for communicat with REST API to a backend python-Server. I try to used the swagger-codegen generated ng2 Client in angular. The Python server is also generated by swagger. The server is working,

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() || {};
                }
            });
    }

My 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

I've try to inject the default.service in my contsructor and after it the browser give message ERROR NO PROVIDER FOR HTTP Injection error ..... I'm totally newbie in ng and ts :-( . After it i define a function getPing for a console log the answer of the server.

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);
      }

}

Solution

  • You've got Http in one place and HttpClient in another. I strongly recommend reading the documentation. I'm going to assume you intend to use HttpClient, but if you want to use Http instead, refer to this other documentation.

    In default.service.ts update your constructor to use HttpClient:

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

    In app.component.ts:

    • remove the HttpClient constructor parameter:

      constructor(private defaultService: DefaultService) {}
      
    • update your getPing() method to actually call the ping() method on default service:

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

      Without the () it's returning a function reference and not invoking the function.

    • remove the import for HttpClientModule. You only need that in the app.module.ts file.

    Your app.module.ts is fine.

    Actually I don't see how that default service will even compile since it seems to be invoking a whole bunch of methods that just ... don't exist.

    As I mentiond before, this is for HttpClient. If you want to use Http you need to use HttpModule instead. Refer to the documentation I linked above, but it's recommended you use HttpClient.