Extracting the year, month, and date values from a ngbDatepicker and sending them over httpClient

Attempting to choose a date using a ngbDatepicker and then sending the year, month, and date values via httpClient to the backend in order to filter a Page of Entities named "Show" based on that date. The backend requires the Integers "year", "month", and "day" as parameters.

The issue I'm currently facing is:

When no date is selected, all Elements are correctly retrieved. However, if a date is selected in the datepicker, an empty list is returned. If I manually input the year, month, and day values in the httpClient params, regardless of the selected date, the list is correctly filtered. This indicates there may be an issue with how the Date from the datepicker is being processed.

Here is my datepicker implementation in the .html file:

<!-- other code -->
<form class="form-inline">
        <div class="form-group">
          <div class="input-group">
            <input class="form-control" placeholder="yyyy-mm-dd"
                   name="dp" ref-selectedDate ngbDatepicker #d="ngbDatepicker" id="picker">
            <div class="input-group-append">
              <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
            </div>
          </div>
        </div>
      </form>
<!-- other code -->
<button (click)="search(selectedDate.value)" type="button" class="btn btn-success"><i class="fas fa-search"></i> Search </button>
<!-- other code -->

The search function in the .ts file:

// other code
private search(selectedDate: Date) {
    this.shows = [];
    this.eventService.getShowPage(this.event.id, selectedDate, this.page, this.pageSize).subscribe(
      (page: Page<Show>) => {
        this.processShowResponse(page.content);
        this.shows = page.content;
        this.totalItems = page.totalElements;
      },
      error => {
        this.defaultServiceErrorHandling(error);
      }
    );
  }
// other code

And my service class:

// other code
getShowPage(eventId: number, searchDate: Date, page: number = 1, size: number = 25): Observable<Page<Show>> {
    this.log('Load shows of event with id ' + eventId + ' on page ' + page);
    let params = new HttpParams().set('page', (page - 1).toString()).set('size', size.toString());
    const url = this.eventBaseUri + '/' + eventId + this.showsUri;

    if (searchDate) {
      params = params.set('year', searchDate.getFullYear().toString());
      params = params.set('month', searchDate.getMonth().toString());
      params = params.set('day',  searchDate.getDate().toString());
    }
    return this.httpClient.get<Page<Show>>(url, {params: params})
      .pipe(map(resp => {
        resp.number++;
        return resp;
      }));
  }
// other code

Answer №1

After some investigation, I discovered that the issue stemmed from the datepicker value being in the format "yyyy-mm-dd", which couldn't be directly converted to a Date object.

To resolve this, I made the following adjustment:

const splitDate = selectedDate.split('-');
year = Number(splitDate[0]);
month = Number(splitDate[1]);
day = Number(splitDate[2]);
searchDate = new Date(year, month, day, 0, 0, 0, 0);

This code snippet was then integrated into the component.ts file.

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 object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

What is the best way to retrieve an array of model objects utilizing a resolver?

I utilize a resolver to fetch data from the server import {Resolve, ActivatedRoute} from "@angular/router"; import {Observable} from "rxjs"; import {RouterStateSnapshot} from "@angular/router"; import {ActivatedRouteSnapshot} from "@angular/router"; imp ...

Issue encountered in Angular-CLI when running the command "ng e2e": inability to access localStorage in protractor tests due to ts-node limitations

In my Angular2 project, I am using ngrx and the @angular/cli: 1.0.0-beta.32.3 version. The structure of my app is very similar to the ngrx example app found at https://github.com/ngrx/example-app. I have integrated localStorage synchronization using the h ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Combining Vue 2 with Bootstrap-vue to create interactive and dynamic attributes

Hello everyone, I'm excited to be taking my first steps in Vue 2 alongside bootstrap-vue. Currently, I am trying to dynamically change the name of an attribute in order to adjust the tooltip position for smaller screen resolutions. The JS code below ...

Is it possible to specify at what point the bootstrap dropdown should convert to a dropup instead?

I have noticed that the bootstrap 4 dropdown transitions to a dropup when there is not enough space at the bottom of the browser window. Is there a way to modify this behavior so that it changes to a dropup when it's, for example, 150px away from the ...

I'm struggling to figure out why my mr-auto isn't functioning properly (built with Bootstrap)

How can I align all my content to the right before the "home" link in this navbar? I've tried using mr-auto but it's not working. Any suggestions? <header class="header_area"> <div class="main-menu"> &l ...

A method for cycling through parent and child objects in JavaScript (Vue.js) and storing them in an array - how to

I have a JSON object structured like this. const jsonData = { "id": "6", "name": "parent", "path": "/", "category": "folder", "fid": "6", "children": [ { ...

How to utilize variables in Bootstrap 4?

After migrating from Bootstrap 3 to Bootstrap 4 and utilizing sass sources that I compile on the go, I encountered an issue with media switches. Specifically, for @media screen and (min-width: $screen-md-min) { padding: 40px 50px; } An error message ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Is there a way to modify an image that has been dynamically inserted in an Angular application?

I'm facing an issue with dynamically added input files in Angular. Whenever I upload a file, it changes all the images of the input files instead of just the one I want to target. How can I resolve this problem? Please help. images = [ {url: &ap ...

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

If you want to use the decorators plugin, make sure to include the 'decoratorsBeforeExport' option in your

Currently, I am utilizing Next.js along with TypeScript and attempting to integrate TypeORM into my project, like demonstrated below: @Entity() export class UserModel extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: number } Unfortun ...

Event triggered before opening the cell editor in ag-Grid

I'm facing a scenario where I have a grid with rows. When a user double clicks on a cell, a cell editor opens up. There are events associated with the cellEditor - cellEditingStarted and cellEditingStopped, but I need an event that triggers just befor ...

Compiling the project using ng build without requiring the download of node

Hey there! Is there a method to execute the ng cli command (ng build --prod) without having to download the npm packages repeatedly? The production build process is becoming very sluggish due to this issue. I am curious to know if there is a way to avoid ...

The local types package cannot be built by react-scripts even though tsc has successfully completed the process

I have developed an application with a TypeScript frontend and backend. To streamline the process, I decided to create a shared types module that contains all the necessary types for both components in one centralized location. Rather than going through th ...

ZOD distinguishes between unions based on two discriminator fields

I need to differentiate between two fields in a schema: enum Action = { CREATE: 'create' } enum ObjectType = { Potatoe: 'potatoe', Tomatoe: 'tomatoe' } export const TestSchema = z.object({ action: z.nativeEnum( ...

Encountering a TS2307 error while trying to import external modules into a TypeScript file

I recently added a new module using npm and now I'm trying to use it in my typescript file. npm install marker-animate-unobtrusive --save import SlidingMarker = require('marker-animate-unobtrusive'); Unfortunately, when I try to access th ...

Steps for including a component in a loop using Angular 6

I'm working on a component that contains two input fields. The goal is to have a row pop up every time the user clicks on the add button, with all the inputs eventually being collected in an array of objects. For example, the component template looks ...