The observable in Angular2's form control valueChanges never reaches completion

Currently, I am working on implementing a simple loader for my search bar to indicate that searching is in progress. My plan was to assign the value "loading" to a variable in the subscribe callback of the valueChanges observable from my form control and then set it to an empty string in the complete callback. However, I have encountered an issue where the complete callback is never executed.

I also attempted to add a callback using finally on the observable, but unfortunately, this callback is also not being triggered.

The code snippet:

searchBox: Control = new Control();
loadingClass: string = "";

constructor() {
    this.searchBox.valueChanges
            .debounceTime(400)
            .distinctUntilChanged()
            .subscribe((text: string) => {
                this.imageSearch = text;
                this.loadingClass = "loading";
            }, (err: Error) => {
                console.log(err);
            }, () => {
                this.loadingClass = "";
                console.log("test");
            });
}

Answer №1

It is common for the observable to never be completed, as it allows you to continuously receive values from your search box. The main goal is to be alerted when the search action has been fully executed.

To achieve this, consider implementing something similar to the following code snippet. Assuming that the searchImage function performs the search and returns an observable:

constructor() {
  this.searchBox.valueChanges
              .debounceTime(400)
              .distinctUntilChanged()
              .flatMap((text:string) => { // <-------
                this.loadingClass = "loading";
                return this.searchImage(text);
              })
              .subscribe((searchResult) => {
                  this.imageSearch = searchResult;
                  this.loadingClass = ""; // <----
              }, (err: Error) => {
                  console.log(err);
              });
}

For more information on how to use the flatMap operator, refer to the following article:

Answer №2

After some reflection, I came to the conclusion that my current method was not working as intended. Upon further investigation, I discovered that I had mistakenly applied debounceTime on my observable. To address this issue, I decided to attach a keyup event listener to my input element. Within this event handler, I updated the value of loadingClass to be "loading". Then, in my subscribe function, I reverted the value back to an empty string.

Answer №3

Understanding Angular2 Forms can make a big difference for many developers. Angular offers two different ways to build forms: Reactive and Template form. Not knowing the distinction between the two approaches could result in messy applications.

The valuesChanges property belongs to the NgModel directive and the FormControl class, so keep that in mind.

To use the reactive approach, you need to import the ReactiveFormsModule (in your.module.ts):

import {ReactiveFormsModule} from '@angular/forms';

@NgModule({
  ...
  imports: [
    ...
    ReactiveFormsModule,
    ...
  ],
  ...
})

This allows you to utilize the [(formControl)] property on your form controls (in template.component.html).

<input type="text" class="form-control" id="searchBox"
       required
       [(formControl)]="searchBox"/> 

For the Template-driven approach, import FormsModule (in your.module.ts):

import {FormsModule} from '@angular/forms';

@NgModule({
  ...
  imports: [
    ...
    FormsModule,
    ...
  ],
  ...
})

This approach has its own form control properties like ngModel (in your.template.ts):

<input type="text" class="form-control" id="searchBox"
       required
       [(ngModel)]="searchBox"/>

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

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Utilize jQuery to toggle classes on multiple elements in web development

I've been struggling to streamline this code I created for the website's navigation. As a novice in Javascript and jQuery, I would appreciate any help or advice. Thank you! Since the page doesn't reload, I have implemented the following met ...

The click function for the responsive navbar hamburger is not functioning properly

Having some trouble with the code not working in responsive mode. I've tested it on a 600px screen and the hamburger button doesn't seem to work (I click it and nothing happens). I've gone through both the CSS and JS multiple times but can&a ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

The array isn't showing any values on the screen

I have been working on a program that will collect values from text boxes and store them in an array. Then, I want to display these values in a table format with the total miles added up. The total miles should be highlighted based on their value. However, ...

Is there a way for me to display an http status code in my fetch error?

I created a React component where I am currently working on setting the state by making a network call. My goal is to eventually pass this state down to other child components, but for now, I am focused on getting everything connected properly. While atte ...

The safeguarding of Angular2 and Laravel against CSRF vulnerabilities

I have come across some interesting articles that I've read recently. The issue I am facing revolves around this particular section of code: <meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}"> I am utilizing Angular2 a ...

Issue with uploading images in Summernote

It seems that my onImageUpload function in the summer note jQuery plugin is not functioning as expected. I am trying to upload an image to a folder location different from the default summernote directory. How can this be handled? index.php <textarea ...

How to retrieve user data based on ID using Angular SDK

I have limited experience with the Angular SDK and lb-service, and I'm unsure about how to retrieve another user's information by their ID within a controller. I am trying to implement a feature for displaying a friend list, where each user only ...

Assign a class to the element only when the second div also has a class

I am trying to create a functionality where I have a dropdown element (Li element) that receives an Active class when its parent div (button) is clicked. When the dropdown element has this class, I want to assign the same class to another div. If the dropd ...

Adding and deleting an item

Currently in the process of developing a web page using javascript, html and css. The page is dedicated to seat booking functionality where users can select and deselect seats. Successfully implemented the feature that displays the ID of the seat when sele ...

Exploring TypeScript Compiler API: Retrieving the resolved type of the 'this' parameter

Is there a way to properly access the type of an explicit 'this' parameter from a ts.Signature using the compiler API? // Code being compiled interface Fn1 { (this: Foo): void; } const fn1: Fn1 = () => {}; interface Fn2<T> { (th ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...

Unable to send a post request using ajax

Section of Form in home.php <div id='googleForm'> <form> <div class='item'> <label class='label'>Full Name</label> <input class=&apos ...

Retrieving posted data in SailsJS

I attempted to retrieve the post data in my controller methods using the code snippet below: req.body.name Unfortunately, this approach did not yield the desired results. ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

How can I limit auto-search results to a specific city in India on Google Maps?

How can we restrict autosearch to only Pune city in India? I attempted the following: autocomplete.setComponentRestrictions( {'country': ['in']},{'city':['Pune']}); ...

What is the process for dynamically inserting a new object into an array of data objects in Vue.js?

I am a beginner with vue.js and currently working on a form. I have an add button in my form, so when the user clicks on it, the same form field will be added to the form. Users can add as many times as they want. Here is my initial data: data () { ret ...

What steps should I follow to integrate AJAX with jQuery in order to store Summernote text in a database?

Seeking clarity on implementing Ajax with Jquery in a web app. I am new to programming with Jquery and struggling to understand existing explanations. I have a summernote text editor where users type values that I want to save in a database. Can someone pr ...

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...