我是angular的新手,我正在尝试通过PrimeNg Toast处理http错误。 我已经创建了可以进行http调用的服务:
@Injectable({
providedIn: 'root'
})
export class AttoService {
apiEnv = environment.apiBase;
constructor(private http: HttpClient, private handleError : HandleErrorService) { }
getAtti() {
return this.http.get<ApiResult<Atto[]>>(this.apiEnv + "Atti")
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError.handleError) // then handle the error;
);
}
}
HandleErrorService:
@Injectable({
providedIn: 'root'
})
export class HandleErrorService {
constructor(private toastService: ToastService) { }
public handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
this.toastService.addSingle;
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
}
正如您在this.toastService.addSingle;
上所看到的,我称呼敬酒服务:
@Injectable({
providedIn: 'root',
})
export class ToastService {
constructor(private messageService: MessageService) { }
addSingle() {
this.messageService.add({severity:'success', summary:'Service Message', detail:'Via MessageService'});
}
}
吐司组件位于app.component.html
中<app-header></app-header>
<app-tab></app-tab>
<app-toast position="top-rigth"></app-toast>
服务由提供商在app.module中注入
@NgModule({
providers:[HandleErrorService, MessageService, ToastService],
但我收到
ERROR TypeError: Cannot read property 'addSingle' of undefined
at CatchSubscriber.push../src/app/service/handle-error.service.ts.HandleErrorService.handleError [as selector] (handle-error.service.ts:18)
你能帮我吗?谢谢
答案 0 :(得分:3)
catchError(this.handleError.handleError) // then handle the error;
像这样使用这一行会更改this
关键字的上下文。
用其中任何一个替换它
catchError(this.handleError.handleError.bind(this))
catchError(err => this.handleError.handleError(err))
答案 1 :(得分:0)
addSingle
是一种方法
this.toastService.addSingle();