catchError 파이프 사용
5186 단어 angularjavascriptrxjstypescript
class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint');
}
}
yourHttpClient.get().subscribe(() => {
// Your logic
},
(error) => {
console.log(error);
}
);
이것의 단점은 모든 구독이 오류를 포착하고 그에 따라 처리해야 한다는 것입니다.
catchError 파이프
대신 HttpClient 자체에서 catchError 파이프를 사용하여 오류를 처리할 수 있습니다. catchError RxJS 파이프에서 볼 수 있듯이 오류가 기록되고 반환되며 구독을 생성할 때 더 이상 오류 논리가 필요하지 않습니다.
class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint').pipe(
catchError((error) => {
console.log(error);
return error;
})
}
}
yourHttpClient.get().subscribe(() => {
// Your logic
}
);
이 예제를 보면 조금 더 개선할 수 있습니다. get 메서드에서 단일 결과만 얻는다는 것을 알고 있습니다. 따라서 get 요청에
first()
연산자를 추가하여 구독을 닫을 수 있습니다.class yourHttpClient {
get<T>() : Observable<T> {
return this.http.get<T>('endpoint').pipe(
catchError((error) => {
console.log(error);
return error;
}),
first()
}
}
Reference
이 문제에 관하여(catchError 파이프 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mitsoe/using-the-catcherror-pipe-3l6g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)