Error: The Select2 query service is not available

I am looking to enhance the search functionality for my select2 dropdown. My goal is to trigger a service call with the search parameters once 3 characters are typed into the search field.

However, when I try to select an option from the dropdown, I encounter an error: TypeError (Cannot read property 'machineService' of null). It seems that the service is not initialized properly before the getSelectOptions method is called.

Below is the HTML code snippet:

<select2 id="inputMachine"
         [data]="machinesModel.data"
         [options]="machinesModel.options"
         [width]="'100%'"
         [disabled]="machinesModel.isDisabled()"
         (valueChanged)="machinesModel.onValueChanged($event); onSelectedMachinesChanged($event)">
</select2>

And here is the relevant component code:

protected getSelectOptions(placeholder: string) {
return {
  allowClear: false,
  placeholder: this.translate.instant(placeholder),
  multiple: true,
  minimumInputLength: 3,
  theme: 'bootstrap',
  query: function (options) {
    this.machineService.findProjections(options.term).subscribe(
      machines => {
        this.setMachines(machines);
        options.callback(this.machinesModel.data);
      },
      error => {
        console.log('Could not load machines: ', error);
      }
    );
  }
};
}

Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

There seems to be a scope issue in the code.

You can resolve this by using a fat arrow function.

protected getSelectOptions(placeholder: string) {
  return {
    allowClear: false,
    placeholder: this.translate.instant(placeholder),
    multiple: true,
    minimumInputLength: 3,
    theme: 'bootstrap',
    query: (options) => {
      this.machineService.findProjections(options.term).subscribe(
        machines => {
          this.setMachines(machines);
          options.callback(this.machinesModel.data);
        },
        error => {
          console.log('Could not load machines: ', error);
        }
      );
    }
  };
}

Answer №2

When utilizing function () {}, the reference of the keyword this will be directed towards the function's context itself. Since the service is declared externally, it remains unknown within this particular scope. Prior to arrow functions, the workaround for this situation was as follows;

var that = this;
{
 // ...
 query: function (options) {
    that.machineService.findProjections(options.term).subscribe();
 }
 // ...
}

However, with the use of ES6 arrow functions (=>), such practice is no longer necessary. Arrow functions leverage what is known as lexical scoping. Consequently, with arrow functions, the scope remains constant, and thus the reference point of this stays intact.

query: (options) => this.machineService.findProjections(options.term).subscribe()

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

The dramatist strategically positioning the cursor at the conclusion of an input field

Currently, I am utilizing playwright for my testing purposes and have encountered a specific issue that I am seeking assistance with. The behavior I need to test is as follows: Applying the bold style to existing text within my input field Verifying that ...

What could be causing this peculiar behavior in my React/TypeScript/MUI Dialog?

My React/TypeScript/MUI application has a dialog that displays multiple buttons. Each time a button is clicked, the dialog function adds the button value to a state array and removes it from the dialog. Although it seems to be working, there is an issue wh ...

Strategies for eliminating nested subscriptions in the search for names

I need assistance with refactoring a component I created to search for GitHub users by login. The current implementation contains nested subscribe blocks, and I would like to rewrite it using rxjs operators without nesting them. You can find the live exam ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

Efficiently resolving Angular's ngFor issues with Float functionality

I am currently developing a rating system that allows for half-star ratings, such as 3.5 or 4.5. Below is the code I have written: <div class="rating"> <i class="icon-star voted" *ngFor="let j of Arr(item.nbEtoile); let i = index;"></i& ...

Is it possible for anyone to access a website's source code using a web browser?

As I navigate the complex world of storing authentication tokens securely using Angular, with the added layer of encryption in the front end before placing it in browser local storage to prevent unauthorized decoding, I have encountered various conflicting ...

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

The `setState` function is failing to change the current value

I'm having an issue with setting State in the dropdown component of semantic-ui-react while using TypeScript in my code. The selected category value is always returning an empty string "". Any suggestions on how to resolve this problem? impo ...

The routerlink feature consistently directs back to the default page

I am facing an issue where my routerlink does not redirect me to the correct path in app.routes.ts when clicked. Even though the routerlinks are set as 'user/teams' and 'user/dashboard' respectively. I can access the pages by directly ...

Trouble with Mui theme not being applied when inside a wrapper component

In my project using React with typescript and MUI version 5.4.2, I have been attempting to manage all styles in a single file by enclosing everything inside my App.tsx component. Problem: The custom MUI theme is not being applied throughout my application ...

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

Debugging with Typescript in Visual Studio Code

I attempted to use the solution found here: how to debug typescript files in visual studio code However, when I set a breakpoint in my .ts files, the debugger indicates that the file is not found. Oddly enough, breakpoints in the .js files are working fin ...

Encountered Angular 7 Error: Unable to access pro due to TypeError

I've encountered an error in my Angular front-end application: Error: index.js:3757 TypeError: Cannot read pro Here's what I have tried so far: I inspected the code but couldn't find the root cause of the error. Running "Ng build" r ...

I encountered an issue with Angular where it is throwing an error stating that the property 'catch' does not exist on the type 'Observable<Object>'

I have been working on an angular application that interacts with a python flask API. During development, I encountered the need to display results passed from the backend. To achieve this, I created an angular service. Below is the code for the angular s ...

Unable to assign the selected attribute to a dynamically loaded Ion-select component in Ionic 2

I'm facing an issue with dynamically loading <ion-select> and setting default selection using the selected attribute. It doesn't seem to work as expected. Can anyone help me understand why? You can view the code on Plunker app/home.page.h ...

Encountering an error when performing unit tests in Angular where the property 'navigate' is undefined

Why am I encountering this error while attempting to run a unit test on a function that needs to be invoked? Here is the code snippet from the .spec.ts file: it(' should call the server when the ok button is clicked, to send the selected code option& ...

Encountering an error with the iconv-lite package in TypeScript code

I recently added the "iconv-lite" package to my project, imported the module, and attempted to use the decode method. However, I encountered the following error: TypeError: Cannot read properties of undefined (reading 'decode') Interestingly, ...

Confirm the existence of duplicates within an Angular reactive form

I am working with a reactive form that looks like this: https://stackblitz.com/edit/angular-form-array-example After clicking the "add credentials" button 3 times, I have 3 sets of elements for username and password. In the first row, I enter the usernam ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...