У меня есть метод в классе обслуживания, который полагается на получение http с использованием идентификатора. Мой метод возвращает Observable с разными свойствами, от которых зависит остальная часть моего приложения.
getCat(catNumber: string): Observable<ICat> {
const url = `${this.serviceURL}Cat/${catNumber}`;
return this._http.get(url).map(this.extractResponse).catch(this.handleError);
}
Проблема, с которой я столкнулся, заключается в том, что метод, вызывающий это, ожидает объект ICat. Если сервер отвечает 404 из-за того, что кота не найдено, остальная часть приложения взрывается. Как я могу проверить код состояния и вернуть то, что мог бы использовать мой другой метод. Даже если это объект Cat с недопустимым идентификатором?
2 ответа
Возможно, вам будет полезна документация по rxjs. Похоже, вы хотите проглотить ошибку 404 и выдать элемент по умолчанию. В вашей функции handleError попробуйте что-то вроде:
private handleError(err: HttpErrorResponse) {
if (err.status == 404) {
let defaultCat : ICat = null; // change to whatever you need
return Observable.Of(defaultCat);
}
else {
// continue handling errors as before
}
}
// Your code:
/*getCat(catNumber: string): Observable<ICat> {
const url = `${this.serviceURL}Cat/${catNumber}`;
return this._http.get(url).map(this.extractResponse).catch(this.handleError);
}*/
// First assumption => You are using Angular 2-4 with RxJS <4 and the HttpModule...
getCat(catNumber: string): Observable<ICat> {
const url = `${this.serviceURL}Cat/${catNumber}`;
return this._http.get(url)
// You need to be doing the same thing as below, whichever way that is.
.map((response) => this.extractResponse(response))
// You were calling a method without binding the context. This causes weird issues with Angular.
.catch((err: HttpErrorResponse) => this.handleError(err));
// You could also do this, but I am leaving it commented out because it is a really old way of doing things:
// .catch(this.handleError.bind(this));
}
// This is assuming that you are using Angular 5 with RxJS 5 and the HttpClientModule...
import { map, catchError } from 'rxjs/operators';
getCat(catNumber: string): Observable<ICat> {
return this._http.get(`${this.serviceURL}Cat/${catNumber}`)
.pipe(
map((response) => this.extractResponse(response)),
catchError((err: HttpErrorResponse) => this.handleError(err))
);
}
Похожие вопросы
Связанные вопросы
Новые вопросы
angular
Вопросы по Angular (не путать с AngularJS), веб-фреймворку от Google. Используйте этот тег для угловых вопросов, которые не относятся к конкретной версии. Для более старой веб-платформы AngularJS (1.x) используйте тег angularjs.