要将表单数据作为服务传递给另一个组件,您可以按照以下步骤进行操作:
@Injectable
装饰器将它标记为可注入的服务。在该服务中,您可以定义一个属性来存储表单数据,并创建一个方法来获取和设置该属性的值。import { Injectable } from '@angular/core';
@Injectable()
export class FormService {
formData: any;
setFormData(data: any) {
this.formData = data;
}
getFormData() {
return this.formData;
}
}
setFormData
方法将表单数据传递给服务。import { Component } from '@angular/core';
import { FormService } from './form.service';
@Component({
selector: 'app-form',
template: `
`,
})
export class FormComponent {
constructor(private formService: FormService) {}
submitForm() {
// 处理表单数据
const formData = {/* 表单数据 */};
// 将表单数据传递给服务
this.formService.setFormData(formData);
}
}
getFormData
方法来获取表单数据。import { Component } from '@angular/core';
import { FormService } from './form.service';
@Component({
selector: 'app-receiver',
template: `
{{ formData | json }}
`,
})
export class ReceiverComponent {
formData: any;
constructor(private formService: FormService) {}
ngOnInit() {
// 获取表单数据
this.formData = this.formService.getFormData();
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormComponent } from './form.component';
import { ReceiverComponent } from './receiver.component';
import { FormService } from './form.service';
@NgModule({
imports: [BrowserModule],
declarations: [FormComponent, ReceiverComponent],
providers: [FormService], // 注册表单服务
bootstrap: [FormComponent, ReceiverComponent],
})
export class AppModule {}
现在,当用户提交表单时,表单数据将被传递给表单服务。然后,接收表单数据的组件可以从表单服务中获取数据并进行处理。