我创建了一个角度应用程序,它通过读取 JSON 动态创建多个表单,如下所示
{
"controls": [
{
"name": "Country",
"label": "Country",
"controlType": "picklist"
},
{
"name": "Pincode",
"label": "Pincode",
"controlType": "number"
},
{
"name": "EmployeeID",
"label": "EmployeeID",
"controlType": "picklist"
}
}
对于控件类型选择列表,我想从 API 读取值并将其与下拉控件绑定。我想知道订阅 API 并将这些值存储在某处的最佳方法是什么,以便在加载表单时,它会将这些值绑定到控件
我在调用 API 的地方编写了服务
*ngFor="let control of formControls; let i = index"
......
.....
if (control.controlType == 'picklist'){
<mat-form-field
appearance="outline"
>
<mat-select [formControlName]="control.name">
@for(item of ArrayList[i]; track item){
<mat-option [value]="item.id">{{ item.cohortName }}</mat-option>
}
</mat-select>
</mat-form-field>
我编写了一个参考服务,它调用各个服务来获取值。但这目前还不是动态的
export class ReferenceService {
CountryList: any;
StudentList: any;
constructor(
private countryService: CountryService,
private studentService: StudentService,
private http: HttpClient
) {
this.countryService.CountryList.subscribe((res) => {
this.CountryList= of(res);
});
this.studentService.StudentList.subscribe((res) => {
this.StudentList= of(res);
});
}
GetList(name: string) {
switch (name.toLowerCase()) {
case 'country': {
return this.CountryList;
}
case 'studentID': {
return this.StudentList;
}
}
}
为了使您的应用程序更加动态和可扩展,您可以修改 ReferenceService 以处理基于控件名称的选项列表值的动态加载。以下是重构服务的方法:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ReferenceService {
private picklistValues: { [key: string]: BehaviorSubject<any[]> } = {};
constructor(private http: HttpClient) {}
getList(name: string): Observable<any[]> {
if (!this.picklistValues[name]) {
this.picklistValues[name] = new BehaviorSubject<any[]>([]);
this.loadPicklistValues(name);
}
return this.picklistValues[name].asObservable();
}
private loadPicklistValues(name: string): void {
// Assuming API endpoint for picklist values is dynamic based on name
const apiUrl = `/api/${name}/values`; // Example API URL
this.http.get<any[]>(apiUrl).subscribe(
(res) => {
this.picklistValues[name].next(res);
},
(error) => {
console.error(`Failed to fetch picklist values for ${name}:`, error);
this.picklistValues[name].error(error);
}
);
}
}
在您的组件中,您可以使用此服务动态获取选项列表值:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { ReferenceService } from 'path-to-reference-service';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
form: FormGroup;
formControls = [
{
name: 'Country',
label: 'Country',
controlType: 'picklist'
},
{
name: 'Pincode',
label: 'Pincode',
controlType: 'number'
},
{
name: 'EmployeeID',
label: 'EmployeeID',
controlType: 'picklist'
}
];
constructor(
private formBuilder: FormBuilder,
private referenceService: ReferenceService
) {}
ngOnInit(): void {
this.form = this.formBuilder.group({});
this.formControls.forEach((control) => {
if (control.controlType === 'picklist') {
this.referenceService.getList(control.name).subscribe((values) => {
this.form.addControl(control.name, this.formBuilder.control(''));
control['values'] = values; // Add values to the control object
});
} else {
this.form.addControl(control.name, this.formBuilder.control(''));
}
});
}
}
希望对你有帮助,别忘了投票哦😁