В учебнике Angular есть предложенный обработчик ошибок, который может возвратить вызывающему значение по умолчанию в случае ошибки.
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
Теперь у меня естьвызов веб-службы с использованием async / await:
public async getItemsAsync() {
try {
return await this.http.get<string[]>("/some/url").toPromise();
}
catch (error) {
this.handleError<string[]>('getItemsAsync', []);
}
}
Что мне нужно изменить, чтобы иметь возможность возвращать значение по умолчанию из моего обработчика ошибок?
private handleError<T>(operation = 'operation', result?: T) {
console.log(`${operation} failed: ${error.message}`);
// let the app keep running by returning an empty result.
return result as T;
}
Должен ли я вернуть Observable
или Promise
? Я попробовал оба, но это не скомпилировано. В настоящее время string[]
не возвращается. Я только получаю undefined
.