如何使RxJ可以观察到错误完成?

时间:2019-03-27 20:47:18

标签: angular rxjs angular-reactive-forms

我有一个angular reactive form,它发出一个简单的GET请求。例如,如果我应该得到某种HTTP错误。可观察的todo$现在已经完成,我无法再更改搜索选项,然后单击以重试搜索。我做了一个stackblitz demo,在演示中,我已将订阅添加到初始化程序中,如果流中有错误,我会捕获它。捕获后,我再次调用初始化程序。这可行,但似乎是错误的错误处理方式。

我已经设置了表单,以便可以取消以前的HTTP请求。

export class AppComponent implements OnDestroy {
  todos;
  loading = false;
  useFakeURL = false;
  todoSub$: Subscription;
  todo$: BehaviorSubject < string > = new BehaviorSubject < string > ('');

  @ViewChild('searchInput') searchInput: ElementRef;

  constructor(private provider: ExampleService) {
    this.init();
  }

  ngOnDestroy() {
    this.todoSub$.unsubscribe();
  }

  search() {
    const value = this.searchInput.nativeElement.value;
    this.todo$.next(value);
    this.useFakeURL = !this.useFakeURL;
  }

  private init(): void {
    this.todoSub$ = this.todo$.pipe(
        filter(val => !!val),
        tap(() => {
          this.loading = true;
        }),
        switchMap(() => this.provider.query(this.todo$.getValue(), this.useFakeURL)),
        catchError(error => {
          this.todo$.next('');
          this.init();
          return of([]);
        }),
      )
      .subscribe(
        todos => {
          this.loading = false;
          this.todos = todos;
        },
        err => {
          this.loading = false;
          this.todos = err;
        }
      );
  }
}

export class ExampleService {

  constructor(private http: HttpClient) {}

  query(todo, useFakeURL: boolean) {
    if (todo === 'all') {
      todo = '';
    }
    const url = useFakeURL ? 'poop' : `https://jsonplaceholder.typicode.com/todos/${todo}`;
    return this.http.get(url);
  }
}
<div class="container">
  <input #searchInput type="text" placeholder="Enter a number or enter 'all' to get all todos">
  <button (click)="search()">Get Todos</button>
</div>
<ul *ngIf="!loading && todos && todos.length">
  <li *ngFor="let todo of todos">
    <pre>
      {{todo | json}}
    </pre>
  </li>
</ul>
<pre *ngIf="!loading && todos && !todos.length">
  {{todos | json}}
</pre>
<div *ngIf="loading" class="loader">... LOADING</div>

2 个答案:

答案 0 :(得分:0)

Angular的Http请求是不可变的。客户端返回的Observable在您订阅时执行实际调用。您订阅的次数越多,将发出的请求越多。那就是所谓的“冷可观察”

如果需要更改请求,则需要HttpClient上的全新可观察对象。

答案 1 :(得分:0)

如@kos所述,我在错误的位置捕获了错误。由于我切换到新的可观察对象,因此我应该在switchMap中捕获错误。 UPDATED-DEMO

search(term: Observable < string > ) {
  return term.pipe(
    filter(val => !!val),
    distinctUntilChanged(),
    debounceTime(500),
    // attached catchError to the inner observable here.
    switchMap(term => this.searchTodo(term).pipe(catchError(() => {
      return of({
        error: 'no todo found'
      });
    }))),
  );
}