【发布时间】:2019-04-27 02:17:43
【问题描述】:
我有一个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>
【问题讨论】:
-
你检查过
retry吗?详情见这篇文章Error handling in RxJS -
我有,不是找请求立即重试,只是希望能改变输入的值,重新搜索。
-
尝试将
catchError放在switchMap内 -
@Kos 有效!谢谢,我以为我在错误的地方发现了错误。
标签: angular rxjs angular-reactive-forms