Как преобразовать формат даты ngbDatepicker в строку onSubmit () формы? - PullRequest
0 голосов
/ 07 октября 2019

Я пытаюсь преобразовать формат даты ngbDatepicker в строку, прежде чем я вызову свой внутренний API для сохранения данных, потому что он допускает дату только в формате строки. Я попытался преобразовать его, используя submittedData.MaturityDate.toString(); и submittedData.RemitDate.toString();, но он не работает.

В настоящее время у меня есть эта форма в моем component.html:

<div class="form-group row">
            <div class="col-sm-6">
              <label for="MaturityDate">Maturity Date</label>
              <div class="input-group">
                <input formControlName="MaturityDate" class="form-control" placeholder="yyyy-mm-dd" name="dp1"
                  ngbDatepicker #dp1="ngbDatepicker" [ngClass]="{ 'is-invalid': submitted && f.MaturityDate.errors }">
                <div class="input-group-append">
                  <button class="btn btn-outline-secondary calendar" (click)="dp1.toggle()" type="button"></button>
                </div>
                <div *ngIf="submitted && !!f.MaturityDate.errors" class="invalid-feedback">
                  <div *ngIf="!!f.MaturityDate.errors.required">Maturity date is required</div>
                </div>
              </div>
            </div>

            <div class="col-sm-6">
              <label for="RemitDate">Remittance Date</label>
              <div class="input-group">
                <input formControlName="RemitDate" class="form-control" placeholder="yyyy-mm-dd" name="dp2"
                  ngbDatepicker #dp2="ngbDatepicker" [ngClass]="{ 'is-invalid': submitted && f.RemitDate.errors }">
                <div class="input-group-append">
                  <button class="btn btn-outline-secondary calendar" (click)="dp2.toggle()" type="button"></button>
                </div>
                <div *ngIf="submitted && !!f.RemitDate.errors" class="invalid-feedback">
                  <div *ngIf="!!f.RemitDate.errors.required">Remittance date is required</div>
            </div>
        </div>
    </div>
</div>

После отправки этой формы,Я вызову следующее в моих component.ts:

onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.accountPayableForm.invalid) {
      return;
    }

    let submittedData = this.accountPayableState;
    submittedData = this.accountPayableForm.value;

    // **TRYING TO CONVERT INPUT TO STRING BUT NOT WORKING
    submittedData.MaturityDate.toString();
    submittedData.RemitDate.toString();
    submittedData.OwningAccountKey = this.currentAccount[0].accountId;

    console.log(submittedData);

    this.loading = true;
    this.accountPayableService
      .submitAccountPayable(submittedData)
      .pipe(first())
      .subscribe(
        (data: AccountPayable) => {
          this.alertService.success(
            'Success! Account payable created with reference ID: ' + data.accountPayableID,
            true
          );
          this.loading = false;
          this.submitted = false;
          this.accountPayableForm.reset();
          document.querySelector('.my-scroll').scrollTo(0, 0);
        },
        error => {
          document.querySelector('.my-scroll').scrollTo(0, 0);
          this.alertService.error('Submission failed, please try again');
          this.loading = false;
        }
      );
  }

Это функция submitAccountPayable() в моих service.ts:

submitAccountPayable(accountPayable: AccountPayableState) {
    return this.http.post(this.issueAccountPayableUrl, accountPayable);
  }

Мои MaturityDate и RemitDate атрибуты в моей AccountPayableState модели представлены в строковом формате, поэтому я подумал, что они будут автоматически преобразованы в строковый формат при вызове этой функции. Вот моя AccountPayableState модель:

export interface AccountPayableState {
  OwningAccountKey: string;
  BuyerAccount: string;
  BuyerCode: number;
  SupplierAccount: string;
  SupplierCode: number;
  PaymentReference: string;
  MaturityDate: string;
  RemitDate: string;
  PaymentAmount: number;
  PaymentCurrency: string;
  PurchaseOrderNumber: string;
}

Это моя полезная нагрузка в консоли для отправки образца, по-видимому, они не в строковом типе, хотя я специально использовал .toString(). Пожалуйста, смотрите MaturityDate и RemitDate ниже:

BuyerAccount: "asdasdasd"
BuyerCode: "123123"
MaturityDate: {year: 2019, month: 10, day: 18}
OwningAccountKey: "e273b89f-c828-41ad-873d-a13bbe63d7c5"
PaymentAmount: "123123123"
PaymentCurrency: "USD"
PaymentReference: "asdasda"
PurchaseOrderNumber: "asdasda"
RemitDate: {year: 2019, month: 10, day: 10}
SupplierAccount: "asdasdasda"
SupplierCode: "123123123"

Любой совет?

Ответы [ 2 ]

1 голос
/ 07 октября 2019

Вы можете просто преобразовать дату с помощью функции;

private dateToString = (date) => `${date.year}-${date.month}-${date.day}`; 

onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.accountPayableForm.invalid) {
      return;
    }

    let submittedData = this.accountPayableState;
    submittedData = this.accountPayableForm.value;

    submittedData.MaturityDate = this.dateToString(submittedData.MaturityDate);
    submittedData.RemitDate= this.dateToString(submittedData.RemitDate);
    submittedData.OwningAccountKey = this.currentAccount[0].accountId;
    ...
0 голосов
/ 07 октября 2019

Объект, возвращаемый из ngbDatepicker, имеет формат по умолчанию, поэтому вам необходимо либо вручную конвертировать его в onSubmit или в модели, либо посмотреть, используя специальный адаптер даты https://ng -bootstrap.github.io/ # / компоненты / DatePicker / примеры # адаптер

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...