Losing object instance in Angular 7 Typescript Service ErrorHandle

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.

Answer №1

It seems like the issue you are facing is related to not binding properly:

@Injectable({
  providedIn: 'root'
})
export class ChildService extends BaseService {
  constructor(alertService: AlertService){
    super(alertService)
  }

  callApiMethod (){
    return this.http.get<Brand>(`ApiUrl`).pipe(
      catchError(this.handleError.bind(this)) // either bind or use arrow function here
    );
  }
}

If your error stems from the line this.msgService.Add(errorMsg); in BaseService, then that might be the root cause.

Answer №2

It is crucial to specify the access specifier of the service within the constructor of the BaseService Class:

constructor(private alertService: AlertService) { }

By doing so, you can properly utilize "this.alertService" without encountering any undefined errors.

Cheers! 🎉

Answer №3

It is important to include access modifiers (public / private) in both the ChildService and BaseService classes. This will ensure that your service reference is available with the property.

Make sure to specify the access modifier in ChildService:

@Injectable({
  providedIn: 'root'
})
export class ChildService extends BaseService {
constructor(**private alertService**: AlertService){
super(alertService)
}

Similarly, add the access modifier in the BaseService class:

 @Injectable({
  providedIn: 'root'
})
export abstract class BaseService {

  constructor(**private msgService**: AlertService) { }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting values from the form array and form group functions in Angular: A step-by-step guide

The code can be found at the link above. export class AppComponent { title = 'Nested FormArray Example Add Form Fields Dynamically'; empForm:FormGroup; constructor(private fb:FormBuilder) { this.empForm=this.f ...

Angular form grouping radio buttons in a unique way

Encountering some unusual behavior with radio buttons and forms currently. In my form, I have 4 radio buttons set up. The issue I'm facing is that when I click on a radio button, it remains enabled permanently. This means I can have all 4 options sel ...

what is the best way to switch classes between 2 buttons using Angular8

Is there a way to create a toggle button effect that adds an 'active' class to BTN1 when it's clicked, and then removes the 'active' class from BTN1 and add it to BTN2 when BTN2 is clicked? Currently, my code only allows for addin ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Sending data from Spark to my Angular8 projectLearn how to seamlessly transfer data from your

I am utilizing Spark 2.4.4 and Scala to retrieve data from my MySQL database, and now I am looking to showcase this data in my Angular8 project. Can anyone provide guidance on the process? I have been unable to locate any relevant documentation so far. ...

Using jQuery in Angular, you can add a div element to hidden elements by appending

So, I have a hidden div that I want to show on button click. And not only do I want to show it, but I also want to append another div to it. The show and hide functionality is working fine, but the appending part seems tricky when dealing with hidden eleme ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Angular 2 is showing an error message: TS1005 - It is expecting a comma

Upon compiling, I encountered the following error: I am unable to locate where a comma needs to be inserted. src/app/navbar.component.ts(29,39): error TS1005: ',' expected. src/app/tache.service.ts(53,53): error TS1005: ',' expected. ...

I attempted to copy the "koa" module from my node_modules folder to a custom typeRoots directory, but it doesn

I want to use Ant Design UI, and I hope to import the script tag with the .min.js label, like this: <script src="//cdn.staticfile.org/react/15.4.1/react.min.js"></script> <script src="//cdn.staticfile.org/react/15.4.1/react-with-addons.min. ...

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...

What is the best way to showcase column data in a React table when the data within the column is an array of objects?

Utilizing a react table to showcase a data table. In the tags column, the goal is to display all tags present in the tags array of objects. Despite several attempts, no success has been achieved yet. Being new to working with tables, any guidance on a more ...

Having trouble compiling the sample JHipster Node.js application

I successfully cloned the jhipster-sample-app-nodejs repository from GitHub (link). Following all the compilation and execution instructions for the application, I have installed the necessary tools (npm, nodejs, yo). However, upon attempting to start th ...

What is the best way to add a header field to a response using NestJS?

I am attempting to create a login function in my code, but encountering an issue: @Post('login') async login(@Body() body: AuthDto, @Res() res: Response) { const loginResponse = await this.authService.login(body); console ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

What is the best way to create a custom isEmpty function that communicates to the TypeScript compiler that a false result indicates the parameter is actually defined?

I have written the following code snippet: export function myIsEmpty(input?: unknown): boolean { if (input === undefined || input === null) { return true; } if (input instanceof Array) { return input.length === 0; } return input == false; ...

Using JavaScript and TypeScript to create a regular expression that meets three different conditions

I need assistance validating a specific element in an XML document using regular expressions. <ConfigOption>value</ConfigOption> Here are the requirements for ConfigOption: Allowed characters include letters, numbers, underscores, and spaces. ...

The repository injected into NestJs using TypeORM suddenly becomes null

In my code, I am fetching Requisition data from an external system using the following approach: init() { const requisitionData = this.loginMb().pipe( map(response => response.data.token), switchMap(loginData => this.getRequisitions(loginD ...

Attempting to retrieve information from Angular API products

The data retrieved from the API is not in the expected format. Within my entity "product," there is a property: public string ArtId { get; set; } In the JSON file used to seed the template database, the property is ArtId. However, when retrieving data ...

Leverage TypeScript to access custom component properties and URL parameters from react-router-dom

In my react-router-dom setup, I have a route structured like this: <Route path="/result/:result" component={ResultsView} audio={audio} speechRecognition={speechRecognition} /> Furthermore, I have a component with specified props as follows ...