In an attempt to show an error message with [ngBootstrap Alert] upon receiving a 404 or 500 response from the Service API, I am encountering an issue.
I intend to utilize the alertComponent for displaying errors and have employed the AlertService.ts for sharing data.
When my API call results in a 404 error, I catch the error and invoke the handleError method defined within my BaseService class.
The problem arises when I inject the Alert service into my BaseService class. Subsequently, when I call the HandleError method, the alert variable loses its instance and defaults to undefined.
BaseService.ts
@Injectable({
providedIn: 'root'
})
export abstract class BaseService {
constructor(msgService: AlertService) { }
public handleError(httpErrorResponse: HttpErrorResponse) {
console.log(httpErrorResponse);
let errorMessage = '';
switch (httpErrorResponse.status) {
case 400:
errorMessage = 'Bad Request detected; please try again later!';
break;
case 404:
const errorMsg = new Alert(AlertType.Danger, 'tracking-not-found');
this.msgService.Add(errorMsg);
break;
case 500:
errorMessage = 'Internal Server Error; please try again later!';
break;
default:
errorMessage = 'Something bad happened; please try again later!';
break;
}
return throwError(errorMessage);
}
ChildService.ts
@Injectable({
providedIn: 'root'
})
export class ChildService extends BaseService {
constructor(alertService: AlertService){
super(alertService)
}
callApiMethod (){
return this.http.get<Brand>(`ApiUrl`).pipe(
catchError(this.handleError)
);
}
}
AlertService.ts
@Injectable({
providedIn: 'root'
})
export class AlertService {
alertMsg: Alert;
constructor() { }
public clear() {
console.log('alert cleared');
this.alertMsg = null;
}
public Add(alert: Alert) {
this.alertMsg = alert;
}
}
Alert.ts
export class Alert {
constructor(public alertType: AlertType,
public msgCode: string,
public icon?: string) { }
}
export enum AlertType {
Success = 'success',
Info = 'info',
Warning = 'warning',
Danger = 'danger',
}
Upon attempting to call the Add method from AlertService, the following Error is thrown:
TypeError: Cannot read property 'Add' of undefined
It seems that the msgService variable somehow gets set to undefined. Any assistance would be appreciated.