Encountered an error trying to access properties that are undefined while working with Ionic Angular, specifically having trouble reading the 'update

As someone who is new to building ionic angular applications (coming from a PHP background), I am currently facing an issue. I have a page with the following code:

export class LicencesTabPage implements OnInit {

  public licencesData: any[] | void;

  constructor(
    protected licenceService: LicencesService,
    protected authService: AuthenticationService,
    protected modelController: ModalController,
    public conversions: DatetimeConversions,
  ) {
  }

  async ngOnInit() {
    this.getData();
  }

  async openDetailedModel(index) {
    const modal = await this.modelController.create({
      component: LicencesDetailedComponent,
      componentProps: {
        itemDetail: this.licencesData[index]
      }
    });

    modal.onDidDismiss().then((modelData) => {
      this.getData();
      if (modelData !== null) {
      }
    });

    return await modal.present();
  }

  protected async getData() {
    const userUUID = await this.authService.getStoredUuid();
    await this.licenceService.getLicences(userUUID).then(res => {
      this.licencesData = JSON.parse(JSON.stringify(res));
    });
  }
}

Users can access a model component by using the openDetailedModel method. Here is the modal component:

export class LicencesDetailedComponent implements OnInit {

  @Input()
  public itemDetail: any = [];
  protected returnValue: any;
  public editItem = false;
  
  // Other declarations omitted for brevity

}

Users can call the updateLicence() method which updates data within the LicencesCommonFunction class. Here is a simplified version of the LicencesCommonFunction class:

export class LicencesCommonFunction implements OnInit {

  public newItem: any;
  protected licencesService: LicencesService;

  // Constructor and other methods omitted for brevity
  
  /**
   *
   * @param form
   */
  updateLicence(form: NgForm) {
      
      this.licencesService.updateLicence(this.newItem).then(() => {
          this.showToast('Updated');
      });
  }
}

When attempting to call the updateLicence method from within the modal component, I encounter the error "Cannot read properties of undefined (reading 'updateLicence')." However, calling it from a page works without issues, indicating that the LicencesService may not be registered when called from within the modal. Any suggestions on how to resolve this issue?

Answer №1

It seems that the usage of dependency injection is inconsistent in your code. In one part, you are correctly injecting dependencies like licenseService, authService, and modelController. However, in another part, your modal component is trying to create its own instances of dependencies.

This can lead to issues, especially if a service like licensesCommonFunctions does not properly instantiate or inject the required services.

To address this issue, I recommend making your common function injectable by using Angular's dependency injection system. This involves annotating the class with @Injectable() and injecting the necessary service through the constructor.

By understanding how dependency injection works in Angular and following best practices, you can avoid errors caused by manually creating service instances instead of leveraging dependency injection.

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

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

Using Pipe directive in Angular 2 with ES5: Error - Directive annotation missing from constructor

My simple pipe looks like this: app.DisplayKeystrokePipe = ng.core .Pipe({ name: "displayKeystroke" }) .Class({ transform: function() { } }); On the other hand, I have a more complex component/directive: app.Drop ...

CORS policy issue with Angular incorporating Agora shows "No 'Access-Control-Allow-Origin'"

I'm new to Angular and currently working on a demo app for proof of concept. The main focus is integrating the Agora SDK into Angular for video calls. I found an integration code for Agora in Angular on GitHub and implemented it as shown below. The `s ...

Following the update to Angular 6, an error was encountered: CssSyntaxError:

Currently, I am in the process of upgrading my Angular 5 application to Angular 6. Following all the necessary steps outlined on update.angular.io, I have encountered a compilation error that persists even after completion of the upgrade process. The err ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

There seems to be an issue with the functionality of Angular Material in Angular9

I've encountered an issue with the material form field, even after importing the necessary modules. Surprisingly, there are no console errors to provide more insight into the problem. { "name": "online-shop", "version": "0.0.0", "scripts": ...

Top choice for React with TypeScript CodeMirror integration

Seeking recommendations for a package that seamlessly integrates with typescript in an existing react application. Specifically, looking to implement codeMirror functionality. Any suggestions? ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Leverage the camera functionality in both native and web applications using Ionic/AngularJS and Cordova

Could you provide some guidance on how to use the Camera feature in both web and native environments? I have tried implementing it using the code snippet below, taken from ng-cordova documentation: $scope.takePicture = function() { var options ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

Tips for implementing 'transloco' on the 'pie-chart' component in an Angular project

Below is the code snippet: .HTML: <div fxFlex> <ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="single0" ...

The event listener for 'end' is not executing in a Node.js Firebase and Nylas Express application

I am currently working on setting up webhooks with Nylas. In their provided example, there is a middleware code that I am implementing in my TypeScript project using Firebase as the endpoint. When testing locally with ngrok, the middleware functions prop ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

Angular universal issue: 404 error code failing to function properly

After numerous attempts, I find myself at a dead end. Our Angular 11 website requires Universal for SEO purposes, and we have set up a 404 page to redirect when necessary. The issue arises when the redirect returns a status code of 200 instead of 404. To ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...