Angular5 / 4 +:使用API​​调用

时间:2018-04-11 08:17:58

标签: angular typescript mean-stack

我正在尝试填充嵌套的ReactiveForm,它被分成几个子窗体组件。 API请求完成后,我可以填充父表单,但不能将子FormArray完全循环到子数据的计数。以下是我的代码中的代码段:

修改视图:edit.component.ts

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss']
})
export class EditComponent implements OnInit {

  public data: Service = new Service({
            id: '',
            title: '',
            description: '',
            service_extras: []
        });    
  public routeParams: any = {};    
  constructor ( 
    private route: ActivatedRoute,
    private service: ServicesService
  ) { }

  ngOnInit() {
    this.setRouteParams();
  }

  setRouteParams() {
    this.route.params.subscribe(params => {
        this.routeParams = params;
      // getting services using api call
        this.getService(this.routeParams);
    });
  }

  getService(params) {
    this.service
    .getService(params.id)
    .subscribe((service: Service) => {
        this.data = service;
    });
  }

}

我在基本edit.component.ts组件中请求数据,并将收到的数据传递给父EditComponent

的子表单组件

edit.component.html

<service-form [serviceFormData]="data"></service-form>

服务form.component.ts

@Component({
    selector: 'service-form',
    templateUrl: './service-form.component.html',
    styleUrls: ['./service-form.component.scss']
})
export class ServiceFormComponent implements OnInit {

    private _serviceFormData = new BehaviorSubject<Service>(null);    
    @Input()
    set serviceFormData(value) {
        this._serviceFormData.next(value);
    }        
    get serviceFormData() {
        return this._serviceFormData.getValue();
    }    
    public service: Service;
    public serviceForm: FormGroup;

    constructor(
        private fb: FormBuilder
    ) { }

    ngOnInit() {    
        this.serviceForm = this.toFormGroup();
        this._serviceFormData.subscribe(data => {
            this.serviceForm.patchValue(data);
        });
    }

    private toFormGroup(): FormGroup {           
        const formGroup = this.fb.group({
            id: [ '' ],
            title: [ '' ],
            description: [ '' ]
        });    
        return formGroup;
    }
}

我在这里通过@Input var的帮助接收数据,通过订阅它的更改,然后将值修补到表单,现在一切正常,因为所有字段在收到数据后都会被填充。问题如下:

服务extra.component.ts

@Component({
  selector: 'service-extra-form',
  templateUrl: './service-extra.component.html',
  styleUrls: ['./service-extra.component.scss']
})
export class ServiceExtraComponent implements OnInit {    
  private _extraFormData = new BehaviorSubject<ServiceExtra[]>([]);

  @Input() serviceForm: FormGroup;    
  @Input() 
  set extraFormData(value: ServiceExtra[]) {
    this._extraFormData.next(value);
  }    
  get extraFormData() {
    return this._extraFormData.getValue();
  }

  public extrasForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit()
  {
    this.serviceForm.addControl('service_extras', new FormArray([]));    
    this._extraFormData.subscribe(data => {
      this.addNew();
      this.extras.patchValue(data);
    });

  }

  private toFormGroup()
  {
    const formGroup = this.fb.group({
      id: [''],
      service_id: [''],
      title: ['']
    });    
    return formGroup;
  }

  public addNew()
  {
    this.extrasForm = this.toFormGroup();        (<FormArray>this.serviceForm.controls.service_extras).push(this.extrasForm);
  }

  public removeThis(i: number)
  {
    (<FormArray>this.serviceForm.controls.service_extras).removeAt(i);
  }


  get extras(): FormArray {
     return this.serviceForm.get('service_extras') as FormArray;
  }

}

以上ngOnInit代码除了添加单个extras表单(即使有两个记录)并填充该表单时,什么也没做,即使我删除了subscribe部分并且仅使用this.addNew(),这种情况也是一样的。我如何知道ServiceExtras有多少条记录,以便我可以将FormGroups添加到FormArray

修改1

Stackblitz Demo

修改2

问题是,如果有两条记录来自API以获得额外的服务,那么我无法生成两个FormGroups并用数据填充它们。因为在渲染时我无法检测到有多少记录要用于来自API的服务附加功能。

2 个答案:

答案 0 :(得分:2)

service-form.component.html中,您将serviceForm.value.service_extras属性绑定到extraFormData。但在service-extra-form组件初始化serviceForm之前没有 service_extras formArray。并在init之后。在service-extra-form组件中,您调用addRow()方法,该方法用一行填充表单:

service-extra.component.ts

 ngOnInit()
  {
    this.serviceForm.addControl('service_extras', new FormArray([]));    
    this._extraFormData.subscribe(data => {
      console.log('service_extra_data', data);
      this.addNew();
      this.extras.patchValue(data);
    });

  }

<强>服务form.component.html:

<service-extra-form [serviceForm]="serviceForm" 
                    [extraFormData]="serviceForm.value.service_extras">
 </service-extra-form> 

将[serviceForm]传递给service-extra-form就足够了。如果您已通过serviceForm.value.service_extras

,为什么通过form

修复,删除额外的сodes。用较少的代码

执行相同的操作

<强> ServiceExtraComponent

export class ServiceExtraComponent implements OnInit {
  @Input() serviceForm: FormGroup;
  @Input() extraFormData: ServiceExtra[];

  public extrasForm: FormGroup;

  constructor(private fb: FormBuilder) { }

 ngOnChanges(data) {
    //console.log('ngOnChanges', data);

    // if changes only extraFormData
    if (data.extraFormData) {
      this.extras.setValue([]); // reset
      let newExtraArr = data.extraFormData.currentValue;

      for (let i = 0; i < newExtraArr.length; i++) {
        this.addNew();
        this.extras.patchValue(newExtraArr);
      }
    }
  } 

  ngOnInit() {
    this.serviceForm.addControl('service_extras', new FormArray([]));
  }

@Input() extraFormData: ServiceExtra[];此处从 api extra_data lyfecycle hook传递ngOnChanges,重置serviceForm的service_extras formArray

StackBlitz Demo

答案 1 :(得分:1)

这是一个修复(stackblitz here

有问题的行为的解释:

您的输入以这种方式声明:

<service-extra-form [serviceForm]="serviceForm" [extraFormData]="serviceForm.value.service_extra"></service-extra-form>

因此输入是表单的值,而不是api的值。

但是当您在对api进行异步调用后填充表单时,“发送”给ServiceExtraComponent的第一个值为undefined,而ServiceExtraComponent ngOnInit中的值为this.addNew(); this.extras.patchValue(data);

data = undefined

patchValue

它在formArray中创建一个新的formGroup,然后使用undefined。

进行修补

因此,当API响应时,您的表单已经使用包含一个项目的formArray创建,因此ServiceExtraComponent会截断您的service_extra数组以匹配您的表单。

更正可能是将API的返回值直接绑定为Input <service-extra-form [serviceForm]="serviceForm" [extraFormData]="serviceFormData.service_extras"></service-extra-form> 又名:

Array.prototype.myFeature = function() {};

var arr = ['some', 'items'];

for (var prop in arr) {
  console.log(prop);
}