0

I have code I cannot edit and code I can.

the code I can't edit is the following :

this.getLogs()
    .toPromise()
    .then((resp: any) => ({
      data: resp['results'],
      totalCount: resp['count']
}));

the code I can edit is the following.

  private getLogs() {
    if (this.id) { // I added this
      params = {};
      params['log_id'] = this.id;
      const url = `${AppGlobal.API_URL}${thislogsUrl}`;
      return this.http.post(
        url,
        params,
        this.authService.getRequestOptions()
      ).pipe(catchError(error => this.handleError(error)));
    } else {  // I added this
      return <---- What do I put here????
    }
  }

I can't for the all the googling in the world find what I am supposed to put on that return that would make the code I can't edit happy.

whatever I return must have the type "toPromise()". but I don't actually want to make an api call in that case (the case where I'm missing the parameter)

I've tried :

  1. return new Observable(string ).delay(500);
  2. return new Promise(null);
  3. return Rx.Observable.of('o').delay(500);
  4. not returning

but none of these are even correct syntax on their own.

The bottom line is I don't want to get an error state. I want it to be silent in that case. preferably do nothing.

tatsu
  • 2,316
  • 7
  • 43
  • 87

1 Answers1

1

toPromise() method exists on Observable class so you have to return an Observable. Since you need to turn it into Promise you can return for example EMPTY that will be turned into a Promise that resolves immediately with value undefined.

You can use eventually of(undefined) as well.

martin
  • 93,354
  • 25
  • 191
  • 226
  • `empy()` is deprecated and is going to be replaced by `EMPTY` constant. https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/empty.ts#L65 – martin Jan 29 '20 at 15:30
  • It depends on what RxJS version you're using. Since RxJS 5.5 the recommended way is using only pipable operators https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md. `EMPTY` is a constant, not a method as `empty()`. That's why it doesn't have any parenthesis. – martin Jan 30 '20 at 08:39
  • could you give an example syntax? is it `new Observable(index/EMPTY)` ? – tatsu Feb 03 '20 at 16:23
  • You import it with `import { EMPTY } from 'rxjs';` and then use it like any other Observable: `EMPTY.pipe(...).subscribe()`. – martin Feb 03 '20 at 21:27