Angular 2/4无法读取initForm()中的对象 [英] Angular 2/4 can't read object in initForm()

查看:139
本文介绍了Angular 2/4无法读取initForm()中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating an edit form in angular and I'm confused about the lifecycle of the object that is returned from my backend server. When I make a call to my service in ngOnInit(), I get workable data. When I assign that to an instance variable, It is undefined in initForm() even though I'm calling initForm() after assigning that data.

如果查看console.log语句,您将看到该对象在ngOnInit()函数内部起作用,而在initForm()中不起作用.我在这里想念什么?如何使整个组件都可以访问this.data?

If you look at the console.log statements you will see that the object works inside the ngOnInit() function but not in initForm(). What am I missing here? How do I make this.data accessible by the entire component?

payee-edit.component.ts:

payee-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:

payee.service.ts:

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


如果我将调用放在订阅中的initForm()上,则页面加载时会出现错误,抱怨需要调用initForm().在触发触发getPayee()调用的事件之前,它不起作用.我现在知道为什么现在要得到这种行为,所以谢谢您的链接.我只需要一些有关我的特定用例的帮助


If I put the call to initForm() inside the subscription, I get an error on page load complaining that initForm() needs to be called. It doesn't work until I fire the event that triggers the getPayee() call. I understand now why I'm getting the behavior now, so thank you for the link. I just need a little help with my specific use case

推荐答案

第一个问题是调用是异步的,因此在检索数据之前调用initForm.此处提供更多信息:如何从angular2中的Observable/http/async调用返回响应?因此,您需要在回调内部调用该方法.

First issue is that the call is asynchronous, so initForm is called before data has been retrieved. More info here: How do I return the response from an Observable/http/async call in angular2? So you need to call the method inside the callback.

测试了代码,因此看起来,当您在回调中添加initForm时,它仍然不起作用,即使 *ngIf="data"设置表单,也是如此.仍然在表单完全构建之前就渲染了表单,这会引发错误.

Tested the code, and so it seems, that when you add the initForm inside the callback it still doesn't work, even though setting the form with *ngIf="data". Still the form gets rendered before the form has been completely built, which throws error.

所以我在这里看到两种可能性.设置一个布尔值,例如showForm,除非showForm为true,否则不呈现表单.在检索数据之后和在构建表单之后,将标志showForm设置为true.

So I see two possibilities here. Set a boolean value, e.g showForm and do not render the form unless showForm is true. You set the flag showForm as true, after data has been retrieved and after the form has been built.

其他选项是使用setValue(或patchValue),在其中检索数据后将数据输入到字段中.这是给你的例子:

Other option would be to use setValue (or patchValue) where you enter the data to the fields after retrieving the data. Here's an example for you:

OnInit中使用空值构建表单:

build the form in your OnInit with empty values:

this.payeeEditForm = new FormGroup({
  'company': new FormControl()
  'first_name': new FormControl()
  'last_name': new FormControl()
  'notes': new FormControl()
})

当检索到数据时,在回调中调用patchForm:

And when retrieved data call patchForm in the callback:

this.subscription = this.payeeService.getPayee(this.id)
   .subscribe(data => {
      this.data = data;
      this.patchForm(); // set the values to the form
   });

和您的patchForm方法:

patchForm() {
  this.payeeEditForm.setValue({
    company: this.data.company,
    first_name: this.data.first_name,
    last_name: this.data.last_name,
    notes: this.data.notes
  });
}

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

This seems to work fine! :) And setting the boolean flag worked too, if you prefer that!

这里是

这篇关于Angular 2/4无法读取initForm()中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆