从网址中检索正确日期的问题

时间:2018-07-17 10:08:54

标签: angular

我目前在从url中的参数检索日期时遇到问题。

我想检索此日期,以便每次单击日期时都将其发送到后端,我检索员工的工作时间并将其显示在客户端。

我可以恢复工作时间,但恢复的日期不会更新,因此它显示了不好的日期。

当我在日期选择器中选择一个日期时,所选的日期会添加到url中,但是使用ActivateRoute的queryParams检索到的日期不会直接更新

示例: 当我单击“ 2018-07-05”时,console.log会显示“星期二”而不是“星期四”。然后,如果您选择其他日期,例如“ 2018-07-09”,则console.log会显示我单击的旧日期,因此“ 2018-07-05-TUESDAY”,依此类推,该日期过时了。

这是我的组件代码:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import * as moment from 'moment';

import { Coach } from '../../coach/shared/coach.model';

import { CoachService } from '../../coach/shared/coach.service';
import { ScheduleService } from '../../schedule/shared/schedule.service';

@Component({
  selector: 'app-create-booking',
  templateUrl: './create-booking.component.html',
  styleUrls: ['./create-booking.component.css']
})
export class CreateBookingComponent implements OnInit {
  coachesList: Coach[] = [];
  coach: Coach;
  coachId: number;
  dateQuery: string;
  availableHours: number[] = [];

  isLinear = true;
  matStepper;

  coachIdControl = new FormControl(null, [Validators.required]);
  dateControl = new FormControl(null, [Validators.required]);

  formGroup = new FormGroup({
    coachId: this.coachIdControl,
    date: this.dateControl
  });

  constructor(
    private _coachService: CoachService,
    private _scheduleService: ScheduleService,
    private _route: ActivatedRoute,
    private _router: Router
  ) {
    {
      this._route.queryParams.subscribe(params => {
        this.coachId = params['coachId'];
        // this.dateQuery = params['date'];
      });
    }
  }

  test(date: MatDatepickerInputEvent<Date>) {
    this._route.queryParams.subscribe(params => {
      this.dateQuery = params['date'];
    });

    const weekDayName = moment(this.dateQuery).format('dddd');
    const weekDayNameToLowerCase = weekDayName.toLowerCase();
    console.log('DAY (DATE):', this.dateQuery);
    console.log('DAY (STRING): ', weekDayNameToLowerCase);

    this._scheduleService
      .getScheduleCoachByDate(this.coachId, weekDayNameToLowerCase)
      .subscribe(arrayOfAvailableHours => {
        this.availableHours = arrayOfAvailableHours;
      });
  }

  ngOnInit() {
    this._coachService.getCoachesList().subscribe(coaches => {
      this.coachesList = coaches;
    });

    this._coachService.getCoachById(this.coachId).subscribe(coach => {
      this.coach = coach;
    });

    // take values from the url and use to populate the form and set current step
    // (you can also use queryMap to use /coach/:id/date/:date url)
    // if the user refreshes the page, the form will repopulate from the query
    // and select the correct step
    this._route.queryParamMap.subscribe(query => {
      if (
        query.has('coachId') &&
        this.coachIdControl.value !== query.get('coachId')
      ) {
        this.coachIdControl.setValue(query.get('coachId'));
        this.matStepper = {};
        this.matStepper.selectedIndex = 1;
      }

      // some translation needed for date
      const date = moment.isMoment(this.dateControl.value)
        ? this.dateControl.value.format('YYYY-MM-DD')
        : null;

      if (query.has('date') && date !== query.get('date')) {
        this.dateControl.setValue(query.get('date'));
        this.matStepper.selectedIndex = 2;
      }
      this.formGroup.updateValueAndValidity();
    });

    // if the form changes, update the query params in the url
    this.formGroup.valueChanges.subscribe(value => {
      this._router.navigate(['/réserver'], {
        queryParams: {
          coachId: value.coachId,
          date: moment.isMoment(value.date)
            ? value.date.format('YYYY-MM-DD')
            : null
        }
      });
    });
  }
}

还有我的html代码:

<form [formGroup]="formGroup">
  <mat-horizontal-stepper linear>
    <mat-step [stepControl]="coachIdControl">

      <h3>Select Coach</h3>

      <div *ngIf="coachesList">
        <mat-form-field>
          <mat-select formControlName="coachId">
            <mat-option *ngFor="let coach of coachesList" value="{{ coach.id }}">{{ coach.first_name }} {{ coach.last_name }}</mat-option>
          </mat-select>
        </mat-form-field>
      </div>
      <div>
        <button mat-raised-button color="primary" matStepperNext type="button">Suivant</button>
      </div>
    </mat-step>
    <mat-step [stepControl]="dateControl">

      <h3>Select date</h3>

      <mat-form-field>
        <input matInput [matDatepicker]="myDatepicker" (dateInput)="test($event)" (dateChange)="test($event)" formControlName="date">
        <mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
        <mat-datepicker #myDatepicker></mat-datepicker>
      </mat-form-field>

      <div *ngFor="let hour of availableHours">
        <button mat-raised-button color="primary">{{ hour }}</button>
      </div>

      <div>
        <button mat-raised-button color="primary" matStepperPrevious type="button">Retour</button>
        <button mat-raised-button color="primary" matStepperNext type="button">Suivant</button>
      </div>
    </mat-step>
    <mat-step>
      <h3>Confirmation</h3>
      <pre>
        <code>{{ formGroup.value | json }}</code>
      </pre>
      <div>
        <button mat-raised-button color="primary" matStepperPrevious type="button">Retour</button>
        <button mat-raised-button color="primary" matStepperNext type="button">Confirmer la réservation</button>
      </div>
    </mat-step>
  </mat-horizontal-stepper>
</form>

非常感谢!

0 个答案:

没有答案