使用Rxjs Observables的Angular Service无法正常工作

时间:2019-08-08 06:48:30

标签: angular typescript

我部署了启用了CORS的云功能。我正在尝试使用Angular服务访问该API,并将json中的数据传递给我在angular组件中的订阅者函数。我试图打一个简单的GET方法。 6x以上版本的rxjs,我不确定自己犯了什么错误,但没有得到任何答复。

服务文件

import { AddClassesDto, ClassesDto } from './classesDtos';
import { AddClientDto, ClientDto } from './clientDtos';
import { AddCourseDto, CourseDto } from './courseDtos';
import { AddUserDto, UserDto } from './userDtos';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { catchError as _observableCatch, mergeMap as _observableMergeMap, catchError, map } from 'rxjs/operators';
import { of as _observableOf, throwError as _observableThrow } from 'rxjs';

import { Observable } from 'rxjs/Observable';

export class ClientServiceProxy {
    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 : "";
    }

GetClientData(): Observable<ClientDto> {
    let url_ = this.baseUrl + "xxxxxxxxxxxxxxxx/getClients";
    url_ = url_.replace(/[?&]$/, "");

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

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

protected processGetAllPermissions(response: HttpResponseBase): Observable<ClientDto> {
    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) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        let result200: any = null;
        let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
        result200 = resultData200 ? ClientDto.fromJS(resultData200) : new ClientDto();
        console.log("Data:"+resultData200);

        return _observableOf(result200);
        }));
    } else if (status !== 200 && status !== 204) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        return throwException("An unexpected server error occurred.", status, _responseText, _headers);
        }));
    }
    return _observableOf<ClientDto>(<any>null);
}
}

客户端DTO

export interface IClientDto {
    abbrev: string | undefined;
    company: string | undefined;
    contact: string | undefined;
    contactDate: string | undefined;
    email: string | undefined;
    phone: string | undefined;
}

export class ClientDto {
    abbrev: string | undefined;
    company: string | undefined;
    contact: string | undefined;
    contactDate: string | undefined;
    email: string | undefined;
    phone: string | undefined;

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

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

    init(data?: any) {
        if(data) {
            this.abbrev = data['abbrev'];
            this.company = data['company'];
            this.contact = data['contact'];
            this.contactDate = data['contactDate'];
            this.email = data['email'];
            this.phone = data['phone'];
        }
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data['abbrev'] = this.abbrev;
        data['company'] = this.company;
        data['contact'] = this.contact;
        data['contactDate'] = this.contactDate;
        data['email'] = this.email;
        data['phone'] = this.phone;
        return data;
    }

    clone() {
        const json = this.toJSON();
        const result = new ClientDto();
        result.init(json);
        return result;
    }
}

1 个答案:

答案 0 :(得分:2)

更改

import { Observable } from 'rxjs/Observable';

import { Observable } from 'rxjs';

我反对这种做法

import { of as _observableOf, throwError as _observableThrow } from 'rxjs';

尤其是如果您希望代码易于阅读。

我删除了您的服务并使其正常工作。从这里开始并添加功能。

import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { catchError , mergeMap ,tap, map } from 'rxjs/operators';
import { of,  throwError  } from 'rxjs';

import { Observable } from 'rxjs';

export class ClientServiceProxy{
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient) {
        this.http = http;
        this.baseUrl = "https://jsonplaceholder.typicode.com/users";
    }

GetClientData(): Observable<any> {

   let url_ = this.baseUrl;

    let options_ = {};
    return this.http.request("get", url_, options_).pipe(
      tap(x => console.log(JSON.stringify(x)))
      );
}