Reputation: 3318
I'm new in angular and I'm trying to manage http error by PrimeNg Toast. I have created the service that make the http call:
@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;
);
}
}
The 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.');
};
}
As you can see with this.toastService.addSingle;
I call the toast service:
@Injectable({
providedIn: 'root',
})
export class ToastService {
constructor(private messageService: MessageService) { }
addSingle() {
this.messageService.add({severity:'success', summary:'Service Message', detail:'Via MessageService'});
}
}
The toast component is in the app.component.html
<app-header></app-header>
<app-tab></app-tab>
<app-toast position="top-rigth"></app-toast>
The service are injected by providers in app.module
@NgModule({
providers:[HandleErrorService, MessageService, ToastService],
but I receive
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)
Can you help me?Thanks
Upvotes: 1
Views: 1182
Reputation:
catchError(this.handleError.handleError) // then handle the error;
Using this line like that changes the context of the this
keyword.
Replace it with either of those
catchError(this.handleError.handleError.bind(this))
catchError(err => this.handleError.handleError(err))
Upvotes: 4