0

I have been trying to get this to work with just one request.

But when the function calls the service it fires the get request twice.

If I remove the switchMap it fires once.

The http request is fired twice it should only fire once.

Any help is appreciated!

loadReports(val: {}) {

  const modelCode = val['modelCode'];

  this._reportService.getReportTypes(modelCode).pipe(
    debounceTime(200),
    distinctUntilChanged(),
    switchMap(() => this._reportService.getReportTypes(modelCode)),
    share(),
  ).subscribe(
    (data) => {
      console.log(data);
    },
    (error) => {
   ...
    },
    () => {
    ...
    }
  );

}

here is the service

getReportTypes(modelCode: string): Observable<any> { 
...
    return this._http.get(apiUrl, httpOptions).pipe(
      tap( _ => console.log('fetched product types')),
      map((resp: Response) => {
      // return data;
          return resp.body['data'].map((item: any[]) => this._adapter.adapt(item));
      }),
      catchError(this.handleError<any>('getReportTypes Error', []))
    );
}

Thanks For your help

Natdrip
  • 1,144
  • 1
  • 11
  • 25
  • `I am using switchMap because the user selects from a drop down.` that makes no sense to me. What you trying to do here, and what problem are you trying to solve? – Reactgular May 24 '19 at 17:27
  • This is just the reason why I am using the switchmap... if the data is still loading and the user selects another item it should cancel what is coming in for the new call. I will remove that comment. It is executing the function twice on every call – Natdrip May 24 '19 at 17:30
  • why did you use switchMap and calling same api again – Reza May 24 '19 at 17:44
  • I think you need to change the title to `Why I am calling a service twice` ;) – Reza May 24 '19 at 17:45
  • @RezaRahmati The function is called when the user selects a value from a drop down. if the user selects before the request is returned then it is possible that the server returns the second request first and the first request second. Thereby you would see the values for the first request for the second user selected value. ie. rq2 -> rs1 ... – Natdrip May 24 '19 at 17:58
  • You *cancel* a previous HTTP request in Angular by *unsubscribing*. You've added the `share()` operator which disables cancelling. – Reactgular May 24 '19 at 18:23
  • @cgTag switchMap cancels the previous subscription and subscribes to the new one. Share is an added artifact that I added in trying to figure this problem out. I have removed share but am still seeing two duplicate calls. – Natdrip May 24 '19 at 18:59
  • When is `loadReports()` called? – Reactgular May 24 '19 at 19:05
  • @cgTag there is an output that emits a call to the parent setSelected(val: any) { ... this.loadReports(val); } ---- this is called on (selectionChange) of the dropdown – Natdrip May 24 '19 at 20:13

0 Answers0