1

I implemented this debug menu in my angular web app to send requests to my backend using a JsonEditor. So far all i required back was the http response to display the response code just to see if the request was successful. However now I have another use-case where I have to send a request and return not only the http response code, but the actual result from the request as well. These requests will affect real data so I can't send the same request twice. Is it possible to return both the http response and result?

  getObject(data: any): Observable<any> {
    let httpOptions = this.kecloakService.buildHeaderWithToken();
    let httpParams = new HttpParams().set("data", data);
    httpOptions = _.extend(httpOptions, httpParams);
    httpOptions = _.extend(httpOptions, { observe: 'response' });

    let resultSubject = new AsyncSubject<any>();

    this.configurationService.loadNetworkConfiguration(false).subscribe((config: NetworkConfiguration) => {
      if (config) {
        let resultObservable = this.http.get(config.backendHostUrl + "ObjectData/", httpOptions);
        //Http response
        //resultObservable.subscribe((response: Response) => {

        //Result 
        resultObservable.subscribe((result: any) => {
          resultSubject.next(result);
          resultSubject.complete();
        }, error => {
          resultSubject.next(error);
          resultSubject.complete();
        });
      }
    });

    return resultSubject;
  }
Dean Strydom
  • 275
  • 5
  • 17
  • Does this answer your question? [Angular4 - Nested Http Calls](https://stackoverflow.com/questions/45926836/angular4-nested-http-calls) – Liam Dec 09 '19 at 11:56

1 Answers1

3

It's an anti-pattern subscribeing inside a Subscription, which is what's happening in the code.

Why not use RxJS Operators like map and switchMap instead.

Here, give this a try:

getObject(data: any): Observable < any > {
  let httpOptions = this.kecloakService.buildHeaderWithToken();
  let httpParams = new HttpParams().set("data", data);
  httpOptions = _.extend(httpOptions, httpParams);
  httpOptions = _.extend(httpOptions, {
    observe: 'response'
  });

  return this.configurationService.loadNetworkConfiguration(false)
  .pipe(
    map((config: NetworkConfiguration) => {
      if (config) {
        return this.http.get(config.backendHostUrl + "ObjectData/", httpOptions);
      } else {
        return of({ error: 'Something went wrong!' });
      }
    })
  );
}

I haven't tested this out but I don't see a reason why it shouldn't work.

Please try it out and let me know if it doesn't :)

Hope this helps.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110