首页 > 解决方案 > (Angular 6)单击按钮两次以工作

问题描述

我有一个表格,我想填写我的数据库信息。为了做到这一点,我制作了一个在我的 NgOnInit 中调用的方法,但是该方法需要调用两次才能工作。
这是方法:

  ngOnInit() {
    this.typeForm = this.formBuilder.group({
      name: [],
      sig: [],
      camp: [],
      stat: [],
      campAt: [],
      campRep: []
    }) 
    this.getData();
  }

  getData(){

   this.getById(100).subscribe(x => this.User = x); 

   this.typeForm = this.formBuilder.group({

    name: [this.User.name],
    sig: [this.User.sig],
    camp: [this.User.camp],
    stat: [this.User.stat],
    campAt: [this.User.campAt],
    campRep: [this.User.campRep]

   })
  };

问题是,当页面加载时,我在控制台中收到以下错误:

无法读取未定义的属性“名称”

奇怪的是,如果我创建一个调用 getData() 的按钮,当单击时,一切正常。如果我从 NgOnInit 中删除 getData(),我必须单击两次上述按钮才能使一切正常工作。Tho,我需要在页面加载后立即填写表格。

这是怎么回事?我该如何解决这个难题?

标签: angularforms

解决方案


Subscribe是异步的,您的其余代码在完成getData()之前执行subscribe

尝试在订阅中移动代码:

      getData(){

       this.getById(100).subscribe(x => {
         this.User = x;

        this.typeForm = this.formBuilder.group({

          name: [this.User.name],
          sig: [this.User.sig],
          camp: [this.User.camp],
          stat: [this.User.stat],
          campAt: [this.User.campAt],
          campRep: [this.User.campRep]

         });

      }); 


   };

推荐阅读