2017-11-01 6 views
1

vielleicht kann jemand helfen. Ich versuche, den Standarddienst in meiner Komponente für die Kommunikation mit der REST-API zu einem Backend-Python-Server zu verwenden. Ich versuche den von swagger-codegen generierten ng2 Client in angular zu verwenden. Der Python-Server wird auch von swagger generiert. Der Server arbeitet,Angular4 und Swagger Client

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

Mein 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

Ich habe versuchen, die default.service in meinem contsructor und nachdem es zu injizieren der Browser gibt Nachricht FEHLER KEIN ANBIETER FÜR HTTP-Injektionsfehler ..... Ich bin total neu in ng und ts :-(. Nachdem ich eine Funktion getPing für eine Konsole loggen Sie die Antwort des Servers.

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

} 

Antwort

0

Sie Http an einem Ort und HttpClient in einem anderen haben. Ich empfehle dringend reading the documentation. Ich gehe davon aus, dass Sie beabsichtigen, HttpClient zu verwenden, aber wenn Sie stattdessen Http verwenden möchten, beziehen Sie sich auf this other documentation.

In default.service.ts Konstruktor aktualisieren verwenden HttpClient:

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

In app.component.ts:

  • den HttpClient Konstruktorparameter entfernen:

    constructor(private defaultService: DefaultService) {} 
    
  • Ihre getPing() Methode aktualisieren tatsächlich die ping() Methode auf Standard-Service zu nennen:

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

    Ohne die () es eine Funktionsreferenz Rückkehr und nicht die Funktion aufgerufen wird.

  • Entfernen Sie den Import für HttpClientModule. Sie brauchen das nur in der Datei app.module.ts.

Ihr app.module.ts ist in Ordnung.

Eigentlich sehe ich nicht, wie dieser Standard-Service sogar kompiliert wird, da es scheint, eine ganze Reihe von Methoden aufzurufen, die einfach ... nicht existieren.

Wie ich zuvor erwähnt habe, ist dies für HttpClient. Wenn Sie Http verwenden möchten, müssen Sie stattdessen HttpModule verwenden. Siehe die oben verlinkte Dokumentation. Es wird jedoch empfohlen, HttpClient zu verwenden.

+0

danke ich habe es behoben. Sie sagen, eine ganze Reihe von Methoden gibt es nicht ... Welche Methoden? Ich dachte, dass ich die Funktion von meinem Swagger-Client aufrufen kann und er pingt den Server? Kannst du vielleicht eine Quelle empfehlen, in der ich mehr über angle4 und die Client-Implementierung lesen kann? – PaddyS

+0

@PaddyS Undefinierte Methoden wie diese: 'this.abortProjectWithHttpInfo (...)'. Das Schlüsselwort "this" gibt an, dass dies eine Klassenmethode ist, aber "DefaultService" hat keine deklarierte Methode namens "abortProjectWithHttpInfo". Wenn dies eine Methode in Ihrer API ist, müssen Sie etwas wie 'this.http.post (" http://example.com/api/abortProjectWithHttpInfo ", ...)' aufrufen. –

+0

der Frozen Vielen Dank für Ihre Hilfe. Ich poste die gesamte default.service-Datei im Kommentar unten mit etwas Text. – PaddyS

0

Das Problem ist, dass in den app.module.ts Sie importieren sind die HttpClientModule von @ Winkel/common/http und in Ihren Diensten, Sie versuchen, die Httpclient von @ Winkel/http zu injizieren. Diese sind eine andere Version als der Http-Client, und die @ eckige/common/http ist die neueste.

Ihren Dienst ändern:

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

danke für die hilfe – PaddyS

0

@Roddy der Frozen das ist meine ganze default.service.ts. Sie sagen, wenn ich diese Methoden habe, muss ich anrufen, aber ich dachte, dass, wenn ich den Server pinge, ich ping von meinem default.service verwenden kann. Ich merke gerade, dass meine eckige App im Browser leer ist. Das HTML wird nicht angezeigt .... das ist frustrierend.

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

}