The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so:

rule.service.ts

@Injectable()
export class RuleService {

    constructor(
        private _resourceService: ResourceService
    ){}

    someMethod(url: string) {
       this._resourceService.getData(url).then((res) => {
          console.log(res);
       }
    }

}

resource.service.ts

@Injectable()
export class ResourceService {

   constructor(
       http: Http
   ) { }

   public getData(url?: string): Promise<T> {
       //some code
   }
}

service being called jQuery :(

private run(input: any, a_parameters: any) {
$("select[name='" + a_parameters[0] + "']").change(function(e: any) {
            return new Promise((resolve) => {
                let array: any[] = [];
                this._resourceService.getData(a_parameters[1]).then(() => {
                    let result: any;
...

However, when attempting to call someMethod from RuleService, a console error occurs:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'getData' of undefined TypeError: Cannot read property 'getData' of undefined //error details..

If anyone can provide guidance on what might be wrong and how to properly implement services within services, I'd greatly appreciate it.

Answer №1

To maintain the context of `this`, it is necessary to use arrow functions

$("select[name='" + a_parameters[0] + "']")
   .change((e: any) => { // <== using arrow functions instead of function expressions
        return new Promise((resolve) => {
            let array: any[] = [];
            this._resourceService.getData(a_parameters[1]).then(() => {

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

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

Unforeseen results arise when using the ng-if directive on a DIV element within an Angular context

@angular/upgrade/static Attempting to upgrade an AngularJS controller to Angular context using UpgradeModule from '@angular/upgrade/static' Encountering issues when changing ng-show to ng-if on span or div elements, as the enclosed content does ...

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Issue with Angular 5 template: "AbstractControl type does not contain property 'length'"

While attempting to compile my Angular project using the command ng build --prod --output-path <my_destination_path>, I encountered a few errors like the following: ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Proper ...

Issue with rest operator behavior in TypeScript when targeting es2018

This specific code snippet functions properly in the TypeScript Playground... class Foo { constructor(...args: any[]) { } static make(...args: any[]): Foo { return new Foo(...args); } } Example However, when trying to incorpora ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

Generating Graphql types for React using graphql-codegen when Apollo Server is in production mode: A step-by-step guide

Everything functions perfectly when backend mode is set to NODE_ENV: development, but in production mode I encounter an error with graphql-codegen: Error on local web server: Apollo Server does not allow GraphQL introspection, but the query contains _sc ...

Issues with the typings for the toPromise function in WebStorm have been identified

I'm encountering an issue with WebStorm not recognizing the typings for the toPromise function on 'rxjs', despite having updated it. Is there a way I can troubleshoot this and fix it? Strangely, the code still runs successfully despite the ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Issue: Directive parameter resolution failure

I've encountered an issue while trying to develop a directive npm package. Previously, I had successfully created packages for @Component, but this is my first attempt at creating one for @Directive. The problem arises when I run ng serve – the bu ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

The silent refresh functionality is currently not functioning as expected in Angular's OAuth OIDC implementation

In my Angular SPA, I am attempting to silently refresh the access token. The authentication with ADFS has been successfully completed and everything is functioning properly. Below is the configuration that I have implemented: oauthService.configure({ ...

Exploring the (*ngFor) Directive to Iterate Through an [object Object]

Attempting to iterate through the array using *ngFor as shown below. let geographicalArea = [{ "_id": "5e77f43e48348935b4571fa7", "name": "Latin America", "employee": { "_id": "5e77c50c4476e734d8b30dc6", "name": "Thomas", ...

Using ES6 import with the 'request' npm module: A Step-by-Step Guide

When updating TypeScript code to ES6 (which runs in the browser and Node server, with a goal of tree-shaking the browser bundle), I am attempting to replace all instances of require with import. However, I encountered an issue... import * as request from ...

Error encountered in Angular Unit Testing: Unable to locate component factory for Component. Have you remembered to include it in @NgModule.entryComponents?

Currently, I am in the process of teaching myself Angular coding but have encountered an issue. While working on developing an app for personal use, I successfully integrated the Angular Material Dialog into a wrapper service without any problems. In one o ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...