0

I have an observable that makes an API call. The API call returns an array of objects in the response.

I am using this observable in multiple places. In most cases, I want the object in the response.

However, in the case of CanDeactivate, I need to 'pre-process' the response to return true or false instead, since CanDeactivate is expected to return Observable.

Is there a way to tap into the response to process it ahead of time (perhaps using the 'tap' operation?)

  canDeactivate(): Observable<boolean> | boolean {

    // Check if Is Being Edited must be removed
    if (this.mustReleaseIsBeingEdited()) {
      return this.updateIsBeingEdited$(false);
    } else {
      return of(true);
    }

  }

  public updateIsBeingEdited$(_id: string, IsBeingEdited: boolean): Observable<Record[]> {

    return this.httpService!.postData(
      `records/_id/${_id}/IsBeingEdited/${IsBeingEdited}`,
      {}
    );

  }
pengz
  • 2,279
  • 3
  • 48
  • 91
  • 3
    Use pipe with [map](https://www.learnrxjs.io/operators/transformation/map.html) – Dino Nov 19 '19 at 15:29
  • 1
    `return this.updateIsBeingEdited$(false).map(resp => { // process as per your need }); – ppgowda4 Nov 19 '19 at 15:34
  • Thanks! I am getting the error message: TS2339: Property 'map' does not exist on type 'Observable' – pengz Nov 19 '19 at 15:36
  • Also tried this: `return this.updateIsBeingEdited$(false) .pipe( map(result => { return true }), catchError(e => console.error(e)) );` but getting this error: TS2322: Type 'void' is not assignable to type 'ObservableInput – pengz Nov 19 '19 at 15:40
  • 2
    in `catchError` you have to return an Observable. `return Observable.throw(e);`. Or if you don't care about it, just remove the `catchError` part – Dino Nov 19 '19 at 15:49
  • Thanks very much! This seems to be working: return this.updateIsBeingEdited$(false) .pipe( map(result => { // Always allow deactivation return true }), catchError(e => { console.error(e); return Observable.throw(e); }) ); – pengz Nov 19 '19 at 15:53

0 Answers0