Angular HttpClient错误处理
Angular HttpClient error handling
在 HttpClient 中发生错误后,我正在为如何执行代码而苦恼。我想知道如何设置在 http 调用失败时关闭加载微调器的标志。
我正在使用 RxJs 5.5.2 和 Angular 5
private fetch(): Observable<LegalTerm[]> {
this.isLoading = true;
return this._http
.get<LegalTerm[]>(AppSettings.LegalTermUrl, { withCredentials: true })
.do(() => this.isLoading = false)
.catch<any, LegalTerm>(this._trace.handleError)
.do(() => this.isLoading = false)
}
所以在快乐的道路上 isLoading = false
可行,但不确定在 catch
之后该怎么做。它不像现在的代码那样工作。我还根据 Angular 文档
使用自定义错误处理程序
public handleError<T>(operation = 'operation', error: any, result?: T) {
// do logging etc
return Observable.of(result as T); // return empty result
}
您可以使用 finally
运算符在 complete/error 事件上将标志更改为 false
。
这可以按如下方式完成:
import { BehaviorSubject }from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/finally';
@Component()
export class FooComponent {
private loadingSub$ = new BehaviorSubeject<boolean>(false);
loading$ = this.loadingSub$.asObservable();
constructor(private fooService: FooService){
}
fetch(){
this.loadingSub$.next(true);
this.fooService.getData()
// notice that getData() returns a stream that isnt infinite
.finally(()=>this.loadingSub$.next(false))
.subscribe(fooData => console.log(fooData)); // error handling not considered
}
}
@Injectable()
export class FooService {
constructor(private http: HttpClient){}
getData(): Observable<any>{
// error handling not considered
return this.http.get('foourl');
}
}
可以找到有关运算符的更多信息here
在 HttpClient 中发生错误后,我正在为如何执行代码而苦恼。我想知道如何设置在 http 调用失败时关闭加载微调器的标志。 我正在使用 RxJs 5.5.2 和 Angular 5
private fetch(): Observable<LegalTerm[]> {
this.isLoading = true;
return this._http
.get<LegalTerm[]>(AppSettings.LegalTermUrl, { withCredentials: true })
.do(() => this.isLoading = false)
.catch<any, LegalTerm>(this._trace.handleError)
.do(() => this.isLoading = false)
}
所以在快乐的道路上 isLoading = false
可行,但不确定在 catch
之后该怎么做。它不像现在的代码那样工作。我还根据 Angular 文档
public handleError<T>(operation = 'operation', error: any, result?: T) {
// do logging etc
return Observable.of(result as T); // return empty result
}
您可以使用 finally
运算符在 complete/error 事件上将标志更改为 false
。
这可以按如下方式完成:
import { BehaviorSubject }from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/finally';
@Component()
export class FooComponent {
private loadingSub$ = new BehaviorSubeject<boolean>(false);
loading$ = this.loadingSub$.asObservable();
constructor(private fooService: FooService){
}
fetch(){
this.loadingSub$.next(true);
this.fooService.getData()
// notice that getData() returns a stream that isnt infinite
.finally(()=>this.loadingSub$.next(false))
.subscribe(fooData => console.log(fooData)); // error handling not considered
}
}
@Injectable()
export class FooService {
constructor(private http: HttpClient){}
getData(): Observable<any>{
// error handling not considered
return this.http.get('foourl');
}
}
可以找到有关运算符的更多信息here