0

So I have a service function which currently looks like this - It is not working, but I feel like its probably close

  deactivateSegment(id, isUsingName?){
    if(isUsingName) {
      return this.getSpecificSegment(id).pipe(concatMap((res: any) => {
        return this.deactivateSegment(res.data.segmentID)
      }))
    } else {
      return this._http.patch(`${this.baseUrl}/segments/${id}/deactivate`, {})
    }
  }

This function can either be called with either an ID or a name as the parameter. If it is called with a name as the parameter, we use the first block of the if statement to first make a call to get the ID, and then use that response to recursively call the deactivateSegment function using the ID rather than the name.

Currently this isn't working as expected though. I think its not returning the correct observable. It seems to just return the getSpecificSegment and then the inner observable doesn't execute, or something like that.

1 Answers1

1

I don't see anything wrong with the condition. I could however suggest few things.

  • Declare types for the parameters and a return type
  • Use double-bang (!!) to check if a variable is defined
  • Use RxJS iif() function to return an observable conditionally. It internally uses the defer() function.
deactivateSegment(id: any, isUsingName?: any): Observable<any> {
  return iif(
    () => !!isUsingName,
    this.getSpecificSegment(id).pipe(
      concatMap((res: any) =>
        this.deactivateSegment(res.data.segmentID)
      )
    ),
    this._http.patch(`${this.baseUrl}/segments/${id}/deactivate`, {})
  );
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • 1
    Thank you very much. I discovered that the issues I was having were actually not because of my implementation. I have implemented your suggestions as well. Thanks for your explanations – Craig Armstrong Jun 18 '21 at 11:52