#javascript #angular #error-handling #this
Вопрос:
Я разрабатываю веб-приложение с использованием Angular 12. Я использовал глобальный обработчик ошибок для обработки всех моих http-ошибок. В моем компоненте портала книг (в модуле книги), когда я вызвал функцию ReaderService (getFavorList) из другого модуля чтения, появилась ошибка: Ошибка типа: this.HandleError не является функцией. Если я вызову эту функцию в том же модуле, это нормально, и если я изменил код ошибки в getFavorList с
catchError(this.handleError('getFavorBookList'))
Для
catchError((err)=>console.log(err))
Эта ошибка также исчезнет, похоже, что у «этого» есть проблема, но я не знаю, как ее исправить, не изменяя функцию обработки ошибок. Я также попытался привязать(это) к this.HandleError, но не исправил проблему.
Ниже приведен код компонента книжного портала:
ngOnInit(): void {
const bookID = this.route.snapshot.paramMap.get('id');
const readerName = this.tokenService.getUsername();
this.commonService.setSubject(readerName);
const readerID = this.readerAuthService.getReaderID();
//Load book info from database
this.bookService.getBook(bookID).subscribe((eBook: Book) => {
if (eBook amp;amp; eBook.bookTitle) {
this.book = eBook;
this.logger.info(`Success load profile of ${bookID}`)
} else {
this.logger.warn(`Failed to load ${bookID} profile from server`);
}
//Load the existing comments and display in page
console.log('The comment length is ' eBook.comments.length);
const existComments = document.querySelector('div.existing-comments');
if (eBook.comments.length > 0) {
this.bookService.getBookComments(bookID).subscribe((comments: BookComment[]) => {
if (comments amp;amp; comments.length > 0) {
this.logger.info(`Success load comments of book ${bookID}`)
for (const item of comments) {
let p1 = document.createElement('p');
p1.className = 'comment-item';
p1.innerHTML = item.comment;
p1.style.fontSize = 'large';
p1.style.fontFamily = 'Times New Roman';
let p2 = document.createElement('p');
p2.className = 'comment-item';
p2.innerHTML = `---by ${item.readerName}`;
p2.style.fontSize = 'large';
p2.style.fontFamily = 'Times New Roman';
existComments.appendChild(p1);
existComments.appendChild(p2);
}
}
});
} else {
let p1 = document.createElement('p');
p1.className = 'comment-item';
p1.innerHTML = 'Be the first person to write comments!';
p1.style.fontSize = 'large';
p1.style.fontFamily = 'Times New Roman';
existComments.appendChild(p1);
}
this.commentForm.setValue({
bookID: bookID,
readerName: readerName,
title: '',
comment: '',
});
});
//If book is in favor book list, disable add fovoriteBook button
let favorInd = false;
this.readerService.getFavorList(readerID).subscribe((data) => {
console.log(data);
if (data amp;amp; data.length > 0) {
for (const item of data) {
if (item.bookID === bookID) {
favorInd = true;
break;
}
}
if (favorInd) {
const addFavorButton = document.querySelector('button.add-favorites') as HTMLButtonElement;
addFavorButton.disabled = true;
}
}
});
}
Ниже приведен код getFavorList:
private handleError: HandleError;
getFavorList(readerID): Observable<any> {
return this.http.get(`/api/reader/${readerID}/getfavourlist`).pipe(
catchError(this.handleError('getFavorBookList')), shareReplay()
)
}
Ниже приведен код части hanleError:
export type HandleError =
<T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;
/** Handles HttpClient errors */
@Injectable()
export class HttpErrorHandler {
constructor(
private router: Router,
private logger: NGXLogger,
) { }
createHandleError = (serviceName = '') => {
return <T>(operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result)
}
/**
* Returns a function that handles Http operation failures.
* This error handler lets the app continue to run as if no error occurred.
* @param serviceName = name of the data service that attempted the operation
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
handleError<T>(serviceName = '', operation = 'operation', result = {} as T) {
return (error: HttpErrorResponse): Observable<T> => {
//Generate error message
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage = `Client side error: ${error.error.message}`;
} else if (error.status === 401) {
errorMessage = `Server return ${error.status} with body "${error.error}"`;
if (error.error.message.includes('Incorrect username or password')) {
window.alert('Incorrect username or password, please check');
} else {
window.alert('Need login to access the contents.');
if (serviceName.toLowerCase().indexOf('reader') != -1) {
this.router.navigateByUrl('/reader/login');
} else {
this.router.navigateByUrl('/librarian/login');
}
}
} else {
errorMessage = `Server return ${error.status} with body "${error.error}"`;
}
//Generate user friendly error log
const errorLog = `HTTP Error in ${serviceName}: ${operation} failed: ${errorMessage}`;
// TODO: send the error to remote logging infrastructure
this.logger.error(errorLog);
return of(result);
};
}
}
Спасибо!
Комментарии:
1. Ты мог бы попробовать
catchError((err) => this.handleError('getFavorBookList')(err))
. С другой стороны, было бы полезно посмотреть, какprivate handleError: HandleError;
создается экземпляр.2. Если вы сделаете консоль. журнал этого.HandleError в getFavorList существует ли он вообще там?
3. Лукаш, твое решение работает, большое тебе спасибо! На самом деле я думал об использовании функции стрелки, чтобы исправить это, но я не поставил (ошибся) в конце…