Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end.

Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpectedly.

@Component({
  selector: 'app-appointment-create',
  templateUrl: './appointment-create.component.html',
  styleUrls: ['./appointment-create.component.css']
})
export class AppointmentCreateComponent implements OnInit {

  appointment: CreateAppointmentDto;
  form: FormGroup;
  private formSubmitted: boolean;
  tasks: Task[];
  availability: Availability[];
  task: number;
  availablemoments: Moment[];

  constructor(
    private titleService: Title,
    private router: Router,
    private appointmentService: AppointmentService,
    private taskService: TasksService,
    private webLogger: WebloggerService,
    private availabilityService: AvailabilityService,
  ) {
    this.appointment = new CreateAppointmentDto();
  }

  dateFilter = (d: Moment): boolean => {
    return this.availability.filter(s => s.timestampstart.isSame(d, 'day')).length >= 1;
  }

  ngOnInit() {
    this.titleService.setTitle('New Appointment');

    this.taskService.getActiveTasks().subscribe(value => {this.tasks = value; });

    this.form = new FormGroup({
      timestampstart: new FormControl(this.appointment.timestampstart, Validators.required),
      daystart: new FormControl(this.appointment.timestampstart, Validators.required),
      location: new FormControl(this.appointment.location, Validators.required),
      description: new FormControl(this.appointment.description, Validators.required),
      paid: new FormControl(false, Validators.required),
      serviceType: new FormControl(this.appointment.serviceTypeId, Validators.required),
      client: new FormControl(this.appointment.clientId, Validators.required),
      assignedUser: new FormControl(this.appointment.assignedUserId, Validators.required),
    });
  }

  onSubmit(event) {
    event.preventDefault();
    this.formSubmitted = true;

    if (this.form.valid) {
      this.form.disable();
      this.appointment.timestampstart = this.form.get('timestampstart').value;
      this.appointment.location = this.form.get('location').value;
      this.appointment.description = this.form.get('description').value;
      this.appointment.paid = this.form.get('paid').value;
      this.appointment.serviceTypeId = this.form.get('serviceType').value;
      this.appointment.clientId = this.form.get('client').value;
      this.appointment.assignedUserId = this.form.get('assignedUser').value;
      this.appointmentService.createNewAppointment(this.appointment)
        .subscribe(value => { this.router.navigate([`/dashboard/appointment/${value.id}/edit`]); });
    } else {
      this.webLogger.error('The form is invalid, please check the values');
    }
  }

  selectTask($event: Event) {
    this.task = Number(this.form.get('serviceType').value);
    this.availabilityService.getAvailabilityForTask(this.task).subscribe(value => {
      this.availability = value;
    });
  }

  setTime($event: Event) {
    this.availablemoments = [];
    const dayAvailability: Availability[] = this.availability.filter(
      s => s.timestampstart.isSame(moment(this.form.get('daystart').value), 'day'));
    const currentDate = dayAvailability.reduce((prev, curr) => prev.timestampstart < curr.timestampstart ? prev : curr).timestampstart;
    dayAvailability.forEach(value => {
      while (value.timestampend.isAfter(currentDate)) {
        if (!this.availablemoments.includes(moment(currentDate))) {
          this.availablemoments.push(moment(currentDate));
        }
        currentDate.add(30, 'minutes');
      }
    });
  }
}

The `availability` array consists of objects with start and end moments.

I anticipate that the output from the second console log should match the first console log.

UPDATE:

This is how the `Availability` class is structured:

export class Availability {
  id: number;
  timestampstart: Moment;
  timestampend: Moment;
  location: string;
  description: string;
  paid: boolean;
  payment: Invoice;
  serviceType: Task;
  client: Client;
  assignedUser: User;

  static serialize(data: any): Availability {
    const user: Availability = Object.assign(new this(), data);
    if (data.hasOwnProperty('timestampstart')) {
      user.timestampstart = moment(data.timestampstart);
    }
    if (data.hasOwnProperty('timestampend')) {
      user.timestampend = moment(data.timestampend);
    }
    if (data.hasOwnProperty('serviceType')) {
      user.serviceType = Task.serialize(data.serviceType);
    }
    if (data.hasOwnProperty('client')) {
      user.client = Client.serialize(data.client);
    }
    if (data.hasOwnProperty('assignedUser')) {
      user.assignedUser = User.serialize(data.assignedUser);
    }
    return user;
  }
}

Answer №1

Solving the issue was a breeze once I realized my mistake. As it turns out, in my Angular project, I mistakenly assigned the formControlName to the wrong HTML tag - instead of attaching it to the select tag where it belonged, I attached it to the option tag. This resulted in fetching a value that wasn't what I had anticipated. To rectify this error, I have made adjustments to the main post which now includes the updated code snippet.

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 the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Designing Checkboxes and Radio Buttons

I am seeking a way to customize the appearance of checked and unchecked checkboxes using images without modifying the HTML structure. I would prefer not to add labels, classes, or IDs to the elements. The provided example only works in Webkit browsers, s ...

The process of executing a PHP file from JavaScript using XMLHttpRequest is experiencing issues on a XAMPP local server

I'm attempting to execute a PHP file using JavaScript. I have my XAMPP server set up and all files saved in the htdocs folder. The PHP file is also stored in the htdocs folder and works correctly when accessed via http://localhost/php_test.php in Chro ...

Tips for accessing Firebase document fields with Angular Firestore (version 7)

My current task involves retrieving a Firebase document property based on the specified model: After successfully locating a document with this code snippet: //Users - collection name, uid - document uid. I am attempting to access the isAdmin property u ...

Ways to designate ROLES within the _user database on Cloudant

I am struggling to figure out how to add Roles to users in the Cloudant user database (_users). Despite searching through Google and Cloudant Docs, I have not been able to find a solution. There is mention of a Cloudant _user db, but I can't seem to u ...

Managing promises with mongoose - Best practices

I am new to using mongoose and I am trying to figure out how to save and handle promises in Node.js using a mongoose schema. In the example below, I am attempting to save data to a collection and handle any errors that may occur. model.js var mongoose = ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

Error in Angular 2 Form Validation

Take a look at this simple form example: <form [ngFormModel]="myForm"> <input type="text" [ngFormControl]="fname" placeholder="First Name"/> <div *ngIf="fname.errors.minlength">First name should be at least 2 characters&l ...

Attempting to grasp the correct method for understanding For loops

Lately, I've been diving into teaching myself Node.JS and it has been quite an enjoyable experience. However, I've hit a frustrating roadblock that is really causing me some grief. For some reason, I just can't seem to grasp the concept of F ...

Injecting script into a webpage and initiating an ajax request prior to receiving a response

Trying to accomplish something a bit complex that I believe is feasible, or perhaps someone could offer a suggestion on how to achieve it. At website A, there is a database containing booking data. At website B, the goal is to display information about w ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...

Utilizing the expression in *ngIf directive in Angular 2 allows for

Currently, I am exploring the possibility of utilizing a function's return value in *ngIf within Angular 2. I conducted an experiment <ion-fab right bottom *ngIf="shouldDisplayFlag()"> Unfortunately, an error is being encountered during this ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

Creating React Context Providers with Value props using Typescript

I'd prefer to sidestep the challenge of nesting numerous providers around my app component, leading to a hierarchy of provider components that resembles a sideways mountain. I aim to utilize composition for combining those providers. Typically, my pro ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...