-1

I have a cloud function deployed with CORS enabled on it. I am trying to hit that API using Angular service and pass that data in json to my subscriber function in angular component. I am trying to hit a simple GET method. The rxjs version in 6+ and i am not sure what mistake i am making but i am not getting any reponse back.

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

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;
    }
}
Ehsan Nissar
  • 643
  • 2
  • 13
  • 35
  • 2
    Are you subscribing to the GET request? – Nicholas K Aug 08 '19 at 06:51
  • @NicholasK yes i am subscribing to it in my component.ts file like this `this._clientService.GetClientData().finally(() => { }) .subscribe((result: any) => { this.clients = result; });` but the problem is my Observable is not returning anything to me – Ehsan Nissar Aug 08 '19 at 06:53
  • 1
    Take a look at this, the finally operator is deprecated now https://stackoverflow.com/questions/40707379/observable-finally-on-subscribe – Robert garcia Aug 08 '19 at 07:06
  • @Robertgarcia okay but right now subscribing to the service is not important for me as you can see that i haved added `console.log("Data:"+resultData200);` in my service and it is returning me nothing. That's the headache for me at the moment – Ehsan Nissar Aug 08 '19 at 07:09
  • Can you post an stackblitz example, its hard to figure this way – Robert garcia Aug 08 '19 at 07:11
  • @Robertgarcia okay let me try posting an example there – Ehsan Nissar Aug 08 '19 at 07:22
  • 1
    @Robertgarcia: A stackblitz may not be the best idea here as the data is dependent on an external API which I doubt will be reachable from it. – Nicholas K Aug 08 '19 at 07:30
  • 1
    Have you checked your Network tab to make sure API is being called successfully? – user Aug 08 '19 at 07:39
  • @user API got called from postman successfully with status 200. – Ehsan Nissar Aug 08 '19 at 07:44
  • 1
    Create a stackblitz and use the api in my answer to get a proof of concept up and running your code has too many things that can go wrong to be debuggable by just looking at it. – SGalea Aug 08 '19 at 07:47
  • @Robertgarcia yes stackblitz is creating problems so i cannot show you more code than this. I have added all necessary things here – Ehsan Nissar Aug 08 '19 at 07:48

1 Answers1

2

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)))
      );
}
SGalea
  • 712
  • 9
  • 18
  • I got this output in console `{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"https://us-central1-donskybackend.cloudfunctions.net/getClients","ok":true,"type":4,"body":{}}` This is not my DTO. I need data in my DTO but you completely removed it – Ehsan Nissar Aug 08 '19 at 07:46
  • 1
    I gave you a starting point, change to your API and start rebuilding your service bit by bit and test it still works after each step, along with introducing your DTO. because imagine your issue is somewhere here let url_ = this.baseUrl + "xxxxxxxxxxxxxxxx/getClients"; url_ = url_.replace(/[?&]$/, ""); how can we possibly discover that ? – SGalea Aug 08 '19 at 07:52