简体   繁体   English

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

[英]Angular Service using Rxjs Observables not working

I have a cloud function deployed with CORS enabled on it. 我部署了启用了CORS的云功能。 I am trying to hit that API using Angular service and pass that data in json to my subscriber function in angular component. 我正在尝试使用Angular服务访问该API,并将json中的数据传递给我在angular组件中的订阅者函数。 I am trying to hit a simple GET method. 我试图打一个简单的GET方法。 The rxjs version in 6+ and i am not sure what mistake i am making but i am not getting any reponse back. 6x以上版本的rxjs,我不确定自己犯了什么错误,但没有得到任何答复。

Service File 服务档案

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

Client DTO 客户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;
    }
}

change 更改

import { Observable } from 'rxjs/Observable';

to

import { Observable } from 'rxjs';

I am against this practice 我反对这种做法

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

Especially if you want your code to be easily readable. 特别是如果您希望代码易于阅读。

I stripped down your Service and got it to work. 我剥离了您的服务并使其正常工作。 Start from here and add functionality. 从这里开始并添加功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM