MomentJS изменяет значение при назначении новой переменной - PullRequest
0 голосов
/ 11 июня 2019

Когда я пытаюсь присвоить момент новой переменной, он меняет значение, а я его не изменяю.

Я перепробовал все, от принудительного использования UTC и настроек часовых поясов. Он просто продолжает изменять значение.

@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');
      }
    });
  }
}

this.availability - это список объектов доступности, которые включают в себя моменты начала и окончания

Я ожидаю, что второй журнал консоли будет возвращен так же, как первый журнал консоли.

UPDATE:

Класс доступности выглядит следующим образом:

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;
  }
}

1 Ответ

0 голосов
/ 12 июня 2019

Я понял это, так как я использовал Angular, я назначил formControlName неправильному HTML-тегу (тегу option вместо select), в результате чего метод get из значения возвратил значение, которого я не ожидал.Я обновил основной пост, чтобы показать весь код.

...