Angular 8 - загрузить данные формы ввода в предыдущий компонент - PullRequest
0 голосов
/ 29 сентября 2019

Я использую Angular версии 8 Cli и у меня есть два отдельных компонента.Первый - это компонент формы, где у меня есть форма, пользователь вводит информацию и отправляет хиты, затем я делаю вызов API службы, чтобы получить список элементов, соответствующих этим результатам, и отобразить их.Как только пользователь выбирает, какую позицию он хочет просмотреть, он нажимает на eventId, и приложение переходит ко второму компоненту, где он может просматривать сводку и PDF-файлы, связанные с этой позицией.Также в этом компоненте 2 они увидят кнопку «Назад к результатам».Я хочу сохранить входные данные пользователя из формы в компоненте 1 при переходе к компоненту 2, а затем, когда они нажмут кнопку «Назад к результатам», приложение вернется к компоненту 1 с предыдущими поисковыми входами Ирезультаты загружены.Я пытался использовать локальное хранилище, а также пытался сохранить на своем сервисе, и, похоже, ничего не работает.Может кто-нибудь помочь с этим?Я вставлю свой код ниже.Если вам нужна дополнительная информация, пожалуйста, дайте мне знать.Заранее спасибо !!

            <ng-container *ngFor="let item of items">
              <tr>
                <td scope="row">{{ item.validated }}</td>
                <td><button class="nav-item nav-link" (click)="onSelectItem(item)">{{ item.eventID }}</button></td>
                <td>{{ item.typeCode }}</td>
                <td>{{ item.facilityname }}</td>
                <td>{{ item.entrydate }}</td>
                <td>{{ item.appID }}</td>
                <td>{{ item.cinNumber }}</td>
                <td>{{ item.lastName }},{{ item.firstName }}</td>
                <td>{{ item.dob }}</td>
                <td>{{ item.countycode }}</td>
                <td>{{ item.aidCode }}</td>
              </tr>
            </ng-container>
          </tbody>

**Component 1 form ts:**

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { RxwebValidators, ReactiveFormConfig, RxFormBuilder } from '@rxweb/reactive-form-validators';
import * as moment from 'moment';
import { Items } from './pdfs';
import { PdfApiService } from '../shared/services/api/pdf-api.service';
import { Facility } from '../shared/form';
import { Router } from '@angular/router';

@Component({
  selector: 'app-cmsp-form',
  templateUrl: './cmsp-form.component.html',
  styleUrls: ['./cmsp-form.component.scss']
})

export class CmspFormComponent implements OnInit {
  facility: Facility[] = [];
  items: Items[] = [];
  lineItem: {};
  previousItems: any;
  customerForm: FormGroup;
  value: any[];
  isValidFormSubmitted = false;
  isLineItemsShown = false;
  entrydate = moment(new Date()).format('YY-MM-DD');
  minDate = new Date(1900, 1, 1);
  maxDate = moment(new Date()).format('YY-MM-DD');
  selectedItem: Items;

  constructor(private formBuilder: RxFormBuilder, private pdfApiService: PdfApiService, private router: Router) {

  }

  loadFacilities() {
    return this.pdfApiService.getFacilities().subscribe((res: Facility[]) => {
      this.facility = res;
      // console.log(this.facility);
    });
  }
  buildForm() {
    this.customerForm = this.formBuilder.group({
      appID: ['', [RxwebValidators.digit(), RxwebValidators.maxLength({ value: 30 })]],
      cinNumber: ['', [RxwebValidators.alphaNumeric(), RxwebValidators.minLength({ value: 9 }), RxwebValidators.maxLength({ value: 13 })]],
      entrydate: [''],
      lastname: ['', [RxwebValidators.required({ conditionalExpression: (x) => x.dob !== '' })]],
      dob: ['', [RxwebValidators.required({ conditionalExpression: (x) => x.lastname !== '' })]],
      facilitynpi: [''],
    });
  }

  ngOnInit(): void {
    this.loadFacilities();
    this.buildForm();
    this.previousItems = this.pdfApiService.searchResults;
    ReactiveFormConfig.set({
      'validationMessage': {
        'required': 'This field is required.',
        'digit': 'This field only accepts numbers.',
        'alphaNumeric': 'This field only accepts letters and numbers.',
        'minLength': 'This field must be 9-13 characters.',
        'maxLength': 'This field must be 9-13 characters.'
      }
    });
  }

  omit_special_char(event: { charCode: any; }) {
    let k: number;
    k = event.charCode;  // k = event.keyCode;  (Both can be used)
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k === 8 || k === 32 || (k >= 48 && k <= 57));
  }
  // convenience getter for easy access to form fields
  get f() { return this.customerForm.controls; }

  onFormSubmit(event: { preventDefault: () => void; }) {
    event.preventDefault();
    this.isValidFormSubmitted = true;
    if (this.customerForm.invalid) {
      return;
    }
    this.getLineItems();
    this.isLineItemsShown = true;
  }

  getLineItems() {
    this.pdfApiService.getLineItems(this.customerForm.value).subscribe((res: Items[]) => {
      this.items = res;
    }, err => {
      console.log(err);
    });
  }

  onSelectItem(item) {
    this.pdfApiService.selectedLineItem = item;
    this.router.navigateByUrl('/results');
    // console.log(this.pdfApiService.selectedLineItem);
  }

  private resetForm() {
    this.isLineItemsShown = false;
    this.customerForm.setValue({
      appID: '',
      cinNumber: '',
      entrydate: '',
      dob: '',
      facilitynpi: 'Choose Facility',
      lastname: ''
    });
  }

  onFormReset() {
    this.resetForm();
  }
}

**Component 2 results html**

<div class="return-btn mt-2">
        <a class="nav-item nav-link"><button type="button" class="btn btn-primary col-12 p-1 m-0" (click)="backToResults()">Return to results</button></a>
      </div>

**Component 2 results ts**

import { Component, OnInit, ViewChild } from '@angular/core';
import { PdfApiService } from '../shared/services/api/pdf-api.service';
import { ModalService } from '../shared/services/modal.service';
import { Router } from '@angular/router';
import value from '*.json';

@Component({
  selector: 'app-cmsp-results',
  templateUrl: './cmsp-results.component.html',
  styleUrls: ['./cmsp-results.component.scss']
})
export class CmspResultsComponent implements OnInit {
  private bodyText: string;
  lineItem: any;
  previousItems: {};
  pdfSrc: any;
  page: number;
  totalPages: number;
  isPdfLoading: boolean;
  pdfToShow: any;
  keys: any;

  constructor(private modalService: ModalService, private pdfApiService: PdfApiService, private router: Router) {
    // console.log(this.pdfApiService.selectedLineItem);
    // console.log(this.pdfSrc);
  }

  ngOnInit() {
    this.lineItem = this.pdfApiService.selectedLineItem;
    this.pdfApiService.getKeys(this.pdfApiService.selectedLineItem.APPKEY).subscribe(res => {
      this.keys = res;
      // console.log(this.keys);
      // this.createPdfFromBlob(data);
      // const file = new Blob([data], { type: 'application/pdf' });
      // const fileURL = URL.createObjectURL(file);
      // window.open(fileURL);
      this.isPdfLoading = true;
    }, error => {
      this.isPdfLoading = false;
      console.log(error);
    });
    this.bodyText = 'This text can be updated in modal 1';
  }

  onSelectedFile(key) {
    this.pdfApiService.getPdf(key).subscribe(data => {
      // console.log(data);
      const file = new Blob([data], { type: 'application/pdf' });
      const fileURL = URL.createObjectURL(file);
      // window.open(fileURL);
      this.pdfSrc = fileURL;
      // console.log(fileURL);
    });
  }
  backToResults(item: any) {
    this.pdfApiService.searchResults = item;
    this.router.navigateByUrl('/');
    console.log(this.pdfApiService.searchResults);
  }

  createPdfFromBlob(pdf: Blob) {
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      this.pdfToShow = reader.result;
    }, false);
    if (pdf) {
      reader.readAsArrayBuffer(pdf);
    }
  }

  openModal(id: string) {
    this.modalService.open(id);
  }

  closeModal(id: string) {
    this.modalService.close(id);
  }
}


1 Ответ

0 голосов
/ 29 сентября 2019
  1. Вы можете использовать тот же метод, что и при передаче информации второму компоненту.Вы можете сохранить данные из первого компонента в this.pdfApiService, а когда вы инициализируете первый компонент, вы можете проверить информацию в сервисе и загрузить в первый компонент.

  2. Службу уведомлений можно использовать для отправки информации обратно первому компоненту из второго компонента.

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