javascript - Angular 8 - 将表单数据输入加载到前一个组件中
问题描述
我正在使用 Angular 8 版 cli,我有两个单独的组件。第一个是表单组件,我有一个表单,用户输入信息并点击提交,然后我进行服务 api 调用以获取与这些结果匹配的项目列表并显示它们。一旦用户选择了他们想要查看的行项目,他们点击 eventId 并且应用程序导航到第二个组件,他们可以在其中查看与该行项目关联的摘要和 pdf。同样在此组件 2 中,他们将看到“返回结果”按钮。我想要做的是在用户导航到组件 2 时从组件 1 的表单中保存用户的输入,然后当他们单击“返回结果”按钮时,应用程序将使用先前的搜索输入导航回组件 1 和结果加载。我尝试使用 localstorage 并尝试保存到我的服务中,但似乎没有任何效果。有人能帮忙吗?我将在下面粘贴一些我的代码。如果您需要任何其他信息,请告诉我。提前致谢!!
<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);
}
}
解决方案
您可以使用与将信息传递给第二个组件相同的方法。您可以将来自第一个组件的数据保存在 this.pdfApiService 中,当您初始化第一个组件时,您可以检查服务中的信息并加载到第一个组件中。
您可以使用通知服务将信息从第二个组件发送回第一个组件。
推荐阅读
- django - 我正在尝试使用 DRF APITestcase 测试基于 DRF 的 API,并遇到此错误 {"detail":"User not found","code":"user_not_found"}'
- reactjs - react-select中AsyncSelect的'defaultInputValue'道具?
- javascript - 如何在三元运算符Typescript中检查数据是否具有定义的类型
- time-complexity - 图灵机上的操作
- android - Android Kotlin java.lang.ClassCastException
- r - 通过多种因素从长格式重塑为宽格式
- python - 使用 pyinstaller 在 main.exe 中转换 main.py 的问题
- hl7-fhir - 有没有办法在 fhir 有几个组织的从业者
- r - 如何从 R 中的 points(fitted()) 函数中提取回归系数
- ios - 编辑文本字段时禁用按钮(多个按钮/网格中的文本字段)