如何在组件中调用角度服务api

问题描述 投票:0回答:1

这是在nswag swagger客户端生成的帮助下从C#控制器自动生成的Angular服务文件。下面的代码提供了所有服务。在组件中,我试图调用getCompanyInfoOption()api。但是我没有收到从控制器发送的响应数据。

/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v13.6.0.0 (NJsonSchema v10.1.18.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable({
providedIn:'root'
})
export class CompanyInfoService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44311";
    }

    getCompanyInfoOption(): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoOption(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoOption(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoOption(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

    addCompanyInfo(companyInfo: CompanyInfoAC): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(companyInfo);

        let options_ : any = {
            body: content_,
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json",
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processAddCompanyInfo(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processAddCompanyInfo(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processAddCompanyInfo(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

    updateCompanyInfo(companyInfo: CompanyInfoAC): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(companyInfo);

        let options_ : any = {
            body: content_,
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json",
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processUpdateCompanyInfo(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processUpdateCompanyInfo(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processUpdateCompanyInfo(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

    getCompanyInfoAnswer(loanApplicationId: string): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info/company-info-answer/{loanApplicationId}";
        if (loanApplicationId === undefined || loanApplicationId === null)
            throw new Error("The parameter 'loanApplicationId' must be defined.");
        url_ = url_.replace("{loanApplicationId}", encodeURIComponent("" + loanApplicationId));
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetCompanyInfoAnswer(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetCompanyInfoAnswer(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetCompanyInfoAnswer(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

    getUser(loanApplicationId: string): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info/get-user/{loanApplicationId}";
        if (loanApplicationId === undefined || loanApplicationId === null)
            throw new Error("The parameter 'loanApplicationId' must be defined.");
        url_ = url_.replace("{loanApplicationId}", encodeURIComponent("" + loanApplicationId));
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processGetUser(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetUser(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processGetUser(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }

    checkUser(email: string | null): Observable<FileResponse | null> {
        let url_ = this.baseUrl + "/api/company-info/check-user/{email}";
        if (email === undefined || email === null)
            throw new Error("The parameter 'email' must be defined.");
        url_ = url_.replace("{email}", encodeURIComponent("" + email));
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Accept": "application/octet-stream"
            })
        };

        return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
            return this.processCheckUser(response_);
        })).pipe(_observableCatch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processCheckUser(<any>response_);
                } catch (e) {
                    return <Observable<FileResponse | null>><any>_observableThrow(e);
                }
            } else
                return <Observable<FileResponse | null>><any>_observableThrow(response_);
        }));
    }

    protected processCheckUser(response: HttpResponseBase): Observable<FileResponse | null> {
        const status = response.status;
        const responseBlob =
            response instanceof HttpResponse ? response.body :
            (<any>response).error instanceof Blob ? (<any>response).error : undefined;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
        if (status === 200 || status === 206) {
            const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
            const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
            const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
            return _observableOf({ fileName: fileName, data: <any>responseBlob, status: status, headers: _headers });
        } else if (status !== 200 && status !== 204) {
            return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            }));
        }
        return _observableOf<FileResponse | null>(<any>null);
    }
}

export class CompanyInfoAC implements ICompanyInfoAC {
    id!: string;
    name!: string;
    cin?: string | undefined;
    addressId!: string;
    companyTypeId!: string;
    sicIndustryId!: string;
    busiinessAgeId!: string;
    employeeStrengthId!: string;
    shareHolderUsers!: ShareHolderUserAC[];
    address!: AddressAC;

    constructor(data?: ICompanyInfoAC) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
        if (!data) {
            this.shareHolderUsers = [];
            this.address = new AddressAC();
        }
    }

    init(_data?: any) {
        if (_data) {
            this.id = _data["id"];
            this.name = _data["name"];
            this.cin = _data["cin"];
            this.addressId = _data["addressId"];
            this.companyTypeId = _data["companyTypeId"];
            this.sicIndustryId = _data["sicIndustryId"];
            this.busiinessAgeId = _data["busiinessAgeId"];
            this.employeeStrengthId = _data["employeeStrengthId"];
            if (Array.isArray(_data["shareHolderUsers"])) {
                this.shareHolderUsers = [] as any;
                for (let item of _data["shareHolderUsers"])
                    this.shareHolderUsers!.push(ShareHolderUserAC.fromJS(item));
            }
            this.address = _data["address"] ? AddressAC.fromJS(_data["address"]) : new AddressAC();
        }
    }

    static fromJS(data: any): CompanyInfoAC {
        data = typeof data === 'object' ? data : {};
        let result = new CompanyInfoAC();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["id"] = this.id;
        data["name"] = this.name;
        data["cin"] = this.cin;
        data["addressId"] = this.addressId;
        data["companyTypeId"] = this.companyTypeId;
        data["sicIndustryId"] = this.sicIndustryId;
        data["busiinessAgeId"] = this.busiinessAgeId;
        data["employeeStrengthId"] = this.employeeStrengthId;
        if (Array.isArray(this.shareHolderUsers)) {
            data["shareHolderUsers"] = [];
            for (let item of this.shareHolderUsers)
                data["shareHolderUsers"].push(item.toJSON());
        }
        data["address"] = this.address ? this.address.toJSON() : <any>undefined;
        return data; 
    }
}

export interface ICompanyInfoAC {
    id: string;
    name: string;
    cin?: string | undefined;
    addressId: string;
    companyTypeId: string;
    sicIndustryId: string;
    busiinessAgeId: string;
    employeeStrengthId: string;
    shareHolderUsers: ShareHolderUserAC[];
    address: AddressAC;
}

export class ShareHolderUserAC implements IShareHolderUserAC {
    user!: UserAC;
    sharePercentage!: number;
    relationship?: string | undefined;

    constructor(data?: IShareHolderUserAC) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
        if (!data) {
            this.user = new UserAC();
        }
    }

    init(_data?: any) {
        if (_data) {
            this.user = _data["user"] ? UserAC.fromJS(_data["user"]) : new UserAC();
            this.sharePercentage = _data["sharePercentage"];
            this.relationship = _data["relationship"];
        }
    }

    static fromJS(data: any): ShareHolderUserAC {
        data = typeof data === 'object' ? data : {};
        let result = new ShareHolderUserAC();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["user"] = this.user ? this.user.toJSON() : <any>undefined;
        data["sharePercentage"] = this.sharePercentage;
        data["relationship"] = this.relationship;
        return data; 
    }
}

export interface IShareHolderUserAC {
    user: UserAC;
    sharePercentage: number;
    relationship?: string | undefined;
}

export class UserAC implements IUserAC {
    id!: string;
    firstName!: string;
    lastName!: string;
    email!: string;
    tin?: string | undefined;
    phone?: string | undefined;

    constructor(data?: IUserAC) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(_data?: any) {
        if (_data) {
            this.id = _data["id"];
            this.firstName = _data["firstName"];
            this.lastName = _data["lastName"];
            this.email = _data["email"];
            this.tin = _data["tin"];
            this.phone = _data["phone"];
        }
    }

    static fromJS(data: any): UserAC {
        data = typeof data === 'object' ? data : {};
        let result = new UserAC();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["id"] = this.id;
        data["firstName"] = this.firstName;
        data["lastName"] = this.lastName;
        data["email"] = this.email;
        data["tin"] = this.tin;
        data["phone"] = this.phone;
        return data; 
    }
}

export interface IUserAC {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    tin?: string | undefined;
    phone?: string | undefined;
}

export class AddressAC implements IAddressAC {
    addressId!: string;
    addressLine1!: string;
    locality!: string;
    administrativeArea!: string;
    country!: string;
    postalCode!: string;
    response!: string;
    responseSource!: string;

    constructor(data?: IAddressAC) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(_data?: any) {
        if (_data) {
            this.addressId = _data["addressId"];
            this.addressLine1 = _data["addressLine1"];
            this.locality = _data["locality"];
            this.administrativeArea = _data["administrativeArea"];
            this.country = _data["country"];
            this.postalCode = _data["postalCode"];
            this.response = _data["response"];
            this.responseSource = _data["responseSource"];
        }
    }

    static fromJS(data: any): AddressAC {
        data = typeof data === 'object' ? data : {};
        let result = new AddressAC();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["addressId"] = this.addressId;
        data["addressLine1"] = this.addressLine1;
        data["locality"] = this.locality;
        data["administrativeArea"] = this.administrativeArea;
        data["country"] = this.country;
        data["postalCode"] = this.postalCode;
        data["response"] = this.response;
        data["responseSource"] = this.responseSource;
        return data; 
    }
}

export interface IAddressAC {
    addressId: string;
    addressLine1: string;
    locality: string;
    administrativeArea: string;
    country: string;
    postalCode: string;
    response: string;
    responseSource: string;
}

export interface FileResponse {
    data: Blob;
    status: number;
    fileName?: string;
    headers?: { [name: string]: any };
}

export class ApiException extends Error {
    message: string;
    status: number;
    response: string;
    headers: { [key: string]: any; };
    result: any;

    constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
        super();

        this.message = message;
        this.status = status;
        this.response = response;
        this.headers = headers;
        this.result = result;
    }

    protected isApiException = true;

    static isApiException(obj: any): obj is ApiException {
        return obj.isApiException === true;
    }
}

function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): Observable<any> {
    if (result !== null && result !== undefined)
        return _observableThrow(result);
    else
        return _observableThrow(new ApiException(message, status, response, headers, null));
}

function blobToText(blob: any): Observable<string> {
    return new Observable<string>((observer: any) => {
        if (!blob) {
            observer.next("");
            observer.complete();
        } else {
            let reader = new FileReader();
            reader.onload = event => {
                observer.next((<any>event.target).result);
                observer.complete();
            };
            reader.readAsText(blob);
        }
    });
}

如何在组件中调用此服务?我正在尝试使用组件的ngOnInit中的subscription方法进行调用

  ngOnInit(): void {
      this.service.getCompanyInfoOption().subscribe(
        value => {
          console.log(value);
        },
        error => console.error(JSON.stringify(error)),
        () => console.log('done')
      );
  }

我在调用getCompanyInfoOption api后得到此输出

Console Log

我的c#控制器

ASP .net core C# controller

下面给出的发送给ok的compantInfoOption的响应类型

conpanyInfoOption type

c# angular nswag
1个回答
0
投票

看来你是。因为您的响应类型为FileResponse,并且在console.log中,您可能会看到此对象。在数据中存储blob的其他内容,如果只需要使用诸如blobToText函数之类的smth(位于生成的文件的末尾),则需要文本解释。

如果我错了,请在问题中添加期望的结果。

© www.soinside.com 2019 - 2024. All rights reserved.