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

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

What method can be used to fetch generic type parameter in typescript?

I am having trouble finding the type of E within the code provided below. class A<E> { getParameterType() { // I need to determine the type of E } } class B { } ** Example ** new A<number>().getParameterType() // number new A<B&g ...

The component is no longer able to locate the imported element when it is being shared

Recently, I imported a component into the shared module in order to use it across 2 different modules. However, upon recompiling the app, an error message appeared stating that the jodit-editor, which is utilized by the shared component, is not recognized ...

What is the best way to create a generic variable and function that utilize the same type?

I am looking for a structure similar to interface propType { value: T action: (value: T) => void } The variable T can be any type, but it must be consistent for both value and action. Using any is not suitable as it could lead to a mismatch in ty ...

When utilizing the ngFor directive with the keyvalue pipe, an error occurs stating that the type 'unknown' cannot be assigned to the type 'NgIterable<any>'

I'm attempting to loop through this object { "2021-11-22": [ { "id": 1, "standard_id": 2, "user_id": 4, "subject_id": 1, "exam_date": "2021-11-22" ...

Exploring SVG Graphics, Images, and Icons with Nativescript-vue

Can images and icons in SVG format be used, and if so, how can they be implemented? I am currently utilizing NativeScript-Vue 6.0 with TypeScript. ...

The DataSource<T> disconnect function from @angular/cdk/collections is not being executed

The disconnect method in the custom DataSource is not triggered when I navigate away from the initializing page. To enable server-side sorting and pagination for a table, I created a custom DataSource. Although everything seems to be functioning correctl ...

Issue with calling Angular2 and jQuery autocomplete component methods from within a spec file

Utilizing the jQuery autocomplete method within an Angular2 component, I have created a service to fetch data from an API. Below is a snippet of myComponent.ts: export class myComponent { private myVar; private binding1; private binding2; constructor( @In ...

Exploring the process of introducing a new property to an existing type using d.ts in Typescript

Within my src/router.ts file, I have the following code: export function resetRouter() { router.matcher = createRouter().matcher // Property 'matcher' does not exist on type 'VueRouter'. Did you mean 'match'? } In an ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Validate object containing both static and dynamic keys

I'm attempting to create a Yup validation schema for an object with the following structure: interface myObject { prop0: Date prop1: { nestedProp1: string nestedProp2: number [key: string]: string | number } } This is what I have tr ...

Retrieve the template parameter from a generic type

While I have experience extracting string from string[], this particular scenario is proving to be quite challenging: type example<T = boolean> = true; // with just "example", how can I retrieve the template parameter "boolean" in this case? type T ...

Having trouble receiving a blob response using HttpClient POST request in Angular 9?

I'm encountering an issue while attempting to receive a zip file as a blob from an HTTP POST request. However, the resolved post method overload is not what I expected. const options = { responseType: 'blob' as const }; Observable<Blob ...

Using MUI DatePicker and react-hook-form to implement a date picker in the format DD/MM/YYYY

I have developed a custom datePicker component that combines react-hook-form and Material UI. However, I am encountering an issue where the values are being displayed in the format: "2024-04-10T22:00:00.000Z" Below is the code snippet: import { Localizati ...

Replacing a component dynamically within another component in Angular 2

I am currently working on integrating a component within another component that has its own view. The component being loaded will be determined dynamically based on specific conditions. Essentially, I am looking to replace one component with another compo ...

Issue: An object with keys {} is not suitable as a React child, causing an error

I am new to TypeScript and seeking help from the community. Currently, I am working on a to-do list project where I am using React and TypeScript together for the first time. However, I encountered an error that I cannot decipher. Any assistance would be g ...

Implementing Angular routing in an ASP.NET Core 2 project

I recently encountered an issue with serving my Angular project within an ASP.NET Core project. After building the Angular app with "ng build --prod" and placing it in the wwwroot directory, I set up the ASP project to serve the site. Since I do not have a ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

When running on localhost, IE11 only shows a white screen while the other browsers function properly

I have recently completed a web-based project and successfully deployed it. The project is running on port 8080. Upon testing in Chrome, Safari, and Firefox, the project functions without any issues, and no errors are displayed in the console. However, wh ...

Challenges arise in communicating between parents and children in Angular 6

I seem to be encountering an issue with parent/child communication in Angular 6. The code appears to be functioning correctly, but I am running into an error in Karma. Here is the specific error message: Failed: Template parse errors: Can't bind to & ...