Angular 8组件间表单数据与搜索结果回显问题求助
Angular 8: 跳转组件时保存表单状态与搜索结果的解决方案
我看了你的代码,发现问题核心是没有正确在Service中持久化表单数据和搜索结果,以及返回组件1时没有主动触发状态恢复逻辑。下面是具体的解决方案:
第一步:完善你的PdfApiService,添加状态存储变量
首先需要在Service中定义专门的变量来共享表单值和搜索结果,确保两个组件能访问到同一份数据:
// pdf-api.service.ts import { Injectable } from '@angular/core'; import { Items } from '../cmsp-form/pdfs'; import { Facility } from '../shared/form'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class PdfApiService { // 你已有的选中项存储 selectedLineItem: Items; // 新增:存储搜索用的表单值 savedFormValue: any; // 新增:存储搜索结果列表 savedSearchResults: Items[]; constructor(private http: HttpClient) { } // 保留你原有的API方法 getFacilities() { return this.http.get<Facility[]>('你的API地址'); } getLineItems(formValue: any) { return this.http.post<Items[]>('你的API地址', formValue); } getKeys(appKey: string) { return this.http.get('你的API地址' + appKey); } getPdf(key: string) { return this.http.get('你的API地址' + key, { responseType: 'blob' }); } }
第二步:修改Component1(CmspFormComponent),实现状态保存与恢复
在组件1中,我们需要在提交表单后保存状态,同时在初始化时检查并恢复之前的状态:
// cmsp-form.component.ts // 保留原有导入 import { Component, OnInit } 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[] = []; customerForm: FormGroup; 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'); constructor( private formBuilder: RxFormBuilder, private pdfApiService: PdfApiService, private router: Router ) { } ngOnInit(): void { this.loadFacilities(); this.buildForm(); // 新增:初始化时恢复之前的状态 this.restorePreviousState(); 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.' } }); } // 新增:恢复状态的方法 private restorePreviousState() { // 恢复表单值 if (this.pdfApiService.savedFormValue) { this.customerForm.setValue(this.pdfApiService.savedFormValue); } // 恢复搜索结果并显示 if (this.pdfApiService.savedSearchResults) { this.items = this.pdfApiService.savedSearchResults; this.isLineItemsShown = true; } } // 保留原有方法,修改getLineItems添加状态保存 getLineItems() { this.pdfApiService.getLineItems(this.customerForm.value).subscribe((res: Items[]) => { this.items = res; // 新增:保存表单值和结果到Service this.pdfApiService.savedFormValue = this.customerForm.value; this.pdfApiService.savedSearchResults = res; }, err => { console.log(err); }); } // 保留其他原有方法(loadFacilities、buildForm、onSelectItem等) }
第三步:修改Component2(CmspResultsComponent)的返回逻辑
返回按钮无需传递参数,直接跳转即可,组件1会自动从Service读取状态恢复:
// cmsp-results.component.ts // 保留原有导入 import { Component, OnInit } from '@angular/core'; import { PdfApiService } from '../shared/services/api/pdf-api.service'; import { ModalService } from '../shared/services/modal.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-cmsp-results', templateUrl: './cmsp-results.component.html', styleUrls: ['./cmsp-results.component.scss'] }) export class CmspResultsComponent implements OnInit { // 保留原有变量 lineItem: any; pdfSrc: any; isPdfLoading: boolean; keys: any; constructor( private modalService: ModalService, private pdfApiService: PdfApiService, private router: Router ) { } ngOnInit() { this.lineItem = this.pdfApiService.selectedLineItem; this.pdfApiService.getKeys(this.lineItem.APPKEY).subscribe(res => { this.keys = res; this.isPdfLoading = true; }, error => { this.isPdfLoading = false; console.log(error); }); } // 修改返回方法,移除无用参数 backToResults() { this.router.navigateByUrl('/'); } // 保留其他原有方法(onSelectedFile、openModal等) }
可选:用localStorage实现页面刷新后仍保留状态
如果需要页面刷新后也能恢复状态,可以在Service中结合localStorage,修改存储逻辑:
// pdf-api.service.ts @Injectable({ providedIn: 'root' }) export class PdfApiService { selectedLineItem: Items; // 用getter/setter封装localStorage操作 get savedFormValue(): any { const value = localStorage.getItem('savedFormValue'); return value ? JSON.parse(value) : null; } set savedFormValue(value: any) { value ? localStorage.setItem('savedFormValue', JSON.stringify(value)) : localStorage.removeItem('savedFormValue'); } get savedSearchResults(): Items[] { const results = localStorage.getItem('savedSearchResults'); return results ? JSON.parse(results) : null; } set savedSearchResults(results: Items[]) { results ? localStorage.setItem('savedSearchResults', JSON.stringify(results)) : localStorage.removeItem('savedSearchResults'); } // 保留原有API方法 }
为什么之前的尝试没生效?
- 使用Service时:你没有在组件1中把表单值和结果存入Service,也没有在初始化时读取Service的数据恢复状态
- 使用localStorage时:可能没有正确序列化/反序列化对象(表单值、数组需要转成JSON字符串才能存储)
按照上述修改后,就能实现跳转时保存状态、返回时自动恢复的需求了。如果还有问题,可以告诉我你的Service原有代码或者其他细节~
内容的提问来源于stack exchange,提问作者Webmystress
相关产品推荐
相关产品推荐

