Encountering difficulty in fetching data from a service with ng-select

Currently, I am utilizing ng-select for a form that allows users to search for activities to add. The ng-select component triggers a function whenever something is typed into the field. This function then calls a service that fetches an array of activities whose names match the input. Subsequently, the ng-select component subscribes to this observable via async.
The main issue I am encountering is that it appears the ng-select is having trouble accessing or subscribing to the Observable. To resolve this, I had to introduce a delay to the Observable returned by the service.

Snippet from HTML:

<label for="class">Activity</label>
   <ng-select [items]="activities$ | async"
              groupBy="type"
              [(ngModel)]="selectedActivity"
              [ngModelOptions]="{standalone: true}" 
              (search)="inputChanged($event)">
   </ng-select>

Corresponding TypeScript code:

activities$!: Observable<Activity[]>;
selectedActivity!: Activity;

private modelChanged: Subject<string> = new Subject<string>();
private searchSubscription!: Subscription;
debounceTime = 500;

constructor(private dataService: DataService) { }

ngOnInit(): void {
  this.initActivitySearchListener();
};

initActivitySearchListener(): void {
   this.searchSubscription = this.modelChanged
      .pipe(
        debounceTime(this.debounceTime),
      )
      .subscribe(input => {
        console.log(input)
        this.updateSearch(input);
   });
}

//Function triggered when typing in activity search bar
inputChanged($event: any) {
   this.modelChanged.next($event.term);
}

updateSearch(term: string) {
   console.log(term);
   this.activities$ = this.dataService.getActivitiesForList(term);
   this.dataService.getActivitiesForList(term).subscribe(data => console.log(data));
}

Data fetching Service:

getActivitiesForList(inputString: string): Observable<Activity[]> {

    let parsedResult: Activity[] = [];

    this.http.get<any>(this.HOST + this.API_URI + 'activity?searchText=' + inputString).subscribe((data) => {
      for (const activity of data) {
        switch (activity.type) {
          case "dungeon":
            let tempBossArray: any[] = [];
            activity.dungeon_boss.forEach((bossObject: any) => {
              tempBossArray.push(bossObject.name);
            });
            parsedResult.push({ id: activity.id, name: activity.name + ' (' + tempBossArray.toString() + ') ' + '[Level ' + activity.level + ']', type: "Dungeon" });
            break;

          case "quest":
            parsedResult.push({ id: activity.id, name: activity.name + ' (' + activity.category + ')', type: "Quest" });
            break;

          default:
            break;
        }
      }
    });
    return of(parsedResult).pipe(delay(100));
  };

If you notice on the last line, there's pipe(delay(100)). If removed, my ng-select won't display any data even though the array is being fetched, as verified through console.log()

Answer №1

I have successfully resolved the issue by realizing that the manual of() was not behaving like a natural Observable in the stream. This was causing a delay in processing the data in the service, resulting in the front end receiving an empty array. To address this, I implemented a solution by processing all data in the pipe() using map() as shown below:

getActivitiesForList(inputString: string): Observable<Activity[]> {
    return this.http.get<any>(this.HOST + this.API_URI + 'activity?searchText=' + inputString).pipe(map((data) => {
      let parsedResult: Activity[] = [];
      for (const activity of data) {
        switch (activity.type) {
          case "dungeon":
            let tempBossArray: any[] = [];
            activity.dungeon_boss.forEach((bossObject: any) => {
              tempBossArray.push(bossObject.name);
            });
            parsedResult.push({
              id: activity.id, 
              name: activity.name + ' (' + tempBossArray.toString() + ') ' + '[Niv. ' + activity.level + ']', 
              type: 'dungeon',
              pretty_type: 'Donjon'
            });
            break;

          case "quest":
            parsedResult.push({
              id: activity.id, 
              name: activity.name + ' (' + activity.category + ')', 
              type: 'quest',
              pretty_type: 'Quête'
            });
            break;

          default:
            break;
        }
      }
      return parsedResult;
    }));
  }

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

Encountered an error trying to access '0' property of an undefined object when iterating through data in angular framework

My API is returning data in the format shown below: "fileName": "data.txt", "onlyInFile1": [ { "_id": "60618e87c2077428e4fedde5", "TERMINAL_ID": "Y6152114", "EXTERNAL_STAN": & ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Changing data types conditionally in Angular using TypeScript

My angular component relies on the API Response for its functionality. I receive these responses from an external API. When there are no errors Data : { Status: string; Data: number; } When an error occurs, this is what I get. Data : { Status: string; ...

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

Step-by-step guide for setting up automatic Tslint in IntelliJ

When working on an Angular project in Intellij, I often encounter numerous tslint errors while coding. Is there a command within Intellij that can automatically fix all of these lint errors? ...

There seems to be an issue with the OpenAPI generator for Angular as it is not generating the multipart form data endpoint correctly. By default

Here is the endpoint that needs to be addressed: @PostMapping(value = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public List<FileReference> handleFileUpload( @RequestPart(value = "file", name = "f ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Unable to run the command npm run env:restart

Currently, I am in the process of running a basic example. The initial setup involved configuring the convector workspace by installing convector-cli and hurley, as well as performing an npm installation. However, when attempting to execute npm run env:r ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

Access the global window variable from index.html within a Vue component

In my Vue project, I am incorporating an Stencil.js component in the following manner: index.html: <script type="module" src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js"> </script> <script> window.addEventLis ...

A destructured object with a Typescript interface

While working on a React / TypeScript project, I encountered an error involving destructuring an object. The issue arises when I try to destructure notificationData within the publish function. An error message stating "Property 'messages' does ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

Guide to executing various datasets as parameters for test cases in Cypress using Typescript

I am encountering an issue while trying to run a testcase with multiple data fixtures constructed using an object array in Cypress. The error message states: TS2345: Argument of type '(fixture: { name: string; sValue: string; eValue: string}) => vo ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

There is a compatibility issue between the module and the engine "node" in this instance

Upon running the command npx create-react-app my-awesome-react-app --template typescript, I encountered the following yarn error: Error [email protected]: The engine "node" is incompatible with this module. Expected version "^6 || ^7 || ^8 || ^9 || ^10 || ...

ngx-slick-carousel: a carousel that loops infinitely and adjusts responsively

I have implemented ngx-slick-carousel to showcase YouTube videos in my project. However, I am facing two main issues. Firstly, the carousel is not infinite, and when the last video is reached, there appears to be white spaces before it loops back to the fi ...