Angular 2/4无法在initForm()中读取对象

时间:2017-04-06 22:48:57

标签: angular angular2-services angular2-http angular2-observables

我正在以角度创建一个编辑表单,我对从后端服务器返回的对象的生命周期感到困惑。当我在ngOnInit()中拨打我的服务时,我得到了可行的数据。当我将其分配给实例变量时,即使我在分配该数据后调用initForm(),它仍未在initForm()中定义。

如果查看console.log语句,您将看到该对象在ngOnInit()函数内部工作,但在initForm()中不起作用。我在这里错过了什么?如何使整个组件可以访问此数据?

收款人edit.component.ts:

export class PayeeEditComponent implements OnInit, OnDestroy {
  public payee: Payee;
  id: number;
  payeeEditForm: FormGroup;
  data: Payee;
  subscription: Subscription;

  constructor(private router: Router, private route: ActivatedRoute, private payeeService: PayeeService) { }
  ngOnInit() {
    this.route.params
      .subscribe(
        (params: Params) => {
          this.id = +params['id'];
          this.subscription = this.payeeService.getPayee(this.id).subscribe(
            data => {
              this.data = data;
              console.log(this.data.company); //THIS WORKS
            }
          );
        }
      );
    this.initForm();

  }
  private initForm() {
    console.log(this.data.company); //THIS RETURNS UNDEFINED
    let payeeCompany = 'this.data.company';
    let payeeFirstName =  'this.data.first_name;'
    let payeeLastName = 'this.data.last_name;'
    let payeeNotes = 'this.data.notes;'

    this.payeeEditForm = new FormGroup({
      'company': new FormControl(payeeCompany),
      'first_name': new FormControl(payeeFirstName),
      'last_name': new FormControl(payeeLastName),
      'notes': new FormControl(payeeNotes)
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

payee.service.ts:

  getPayee(id: number) {
    return this.http.get(`http://localhost:3000/payees/${id}`)
    .map(data => data.json());
  }

编辑:
如果我在订阅中调用initForm(),我会在页面加载时收到错误,抱怨需要调用initForm()。在我触发触发getPayee()调用的事件之前,它不起作用。我现在明白为什么我现在得到这个行为,所以谢谢你的链接。我只需要对我的具体用例提供一些帮助

2 个答案:

答案 0 :(得分:1)

第一个问题是调用是异步的,因此在检索数据之前调用initForm。更多信息:How do I return the response from an Observable/http/async call in angular2?所以你需要在回调中调用方法。

测试代码,看来,当你在回调中添加initForm时,它仍然无法正常工作,即使使用{{1>设置表单}}。在表单完全构建之前,表单仍会呈现,这会引发错误。

所以我在这看到两种可能性。设置一个布尔值,例如*ngIf="data",除非showForm为真,否则不要渲染表单。在构建表单后,在检索到数据之后,将标记showForm设置为true。

其他选项是使用showForm(或setValue),您可以在检索数据后将数据输入到字段中。以下是您的一个例子:

使用空值在patchValue中构建表单:

OnInit

当检索到的数据在回调中调用this.payeeEditForm = new FormGroup({ 'company': new FormControl() 'first_name': new FormControl() 'last_name': new FormControl() 'notes': new FormControl() }) 时:

patchForm

和您的this.subscription = this.payeeService.getPayee(this.id) .subscribe(data => { this.data = data; this.patchForm(); // set the values to the form }); - 方法:

patchForm

这似乎工作正常! :)如果您愿意,也可以设置布尔标志!

这是

Demo

答案 1 :(得分:0)

您为subscribe方法提供的回调晚于initForm方法执行。因为http调用需要X个时间。

您可以做的是将所有属性绑定到输入中的([ngModel])。