(Angular 6) Click the button twice in order to work












0















I have a form that i want to get filled with my database info.
In order to do that, i've made a method wich is called in my NgOnInit, but that method needs to be called twice in order to work.

This is the method:



  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]

})
};


The thing is, when the page loads, i get the following error in the console:




Cannot read property 'name' of undefined




But the weird thing is, if i make a button that calls getData(), when clicked, everything works fine. If i remove getData() from NgOnInit, I have to click twice the said button in order for everything to work. Tho, i need the form to get filled as soon as the page loads.



What's goin on here? How can I fix this conundrum?










share|improve this question


















  • 1





    Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

    – penleychan
    Nov 28 '18 at 18:03











  • How can i make the page wait for the >this.user< to be resolved?

    – CH4B
    Nov 28 '18 at 18:05











  • You can either put it inside your subscribe or on its complete callback

    – penleychan
    Nov 28 '18 at 18:08
















0















I have a form that i want to get filled with my database info.
In order to do that, i've made a method wich is called in my NgOnInit, but that method needs to be called twice in order to work.

This is the method:



  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]

})
};


The thing is, when the page loads, i get the following error in the console:




Cannot read property 'name' of undefined




But the weird thing is, if i make a button that calls getData(), when clicked, everything works fine. If i remove getData() from NgOnInit, I have to click twice the said button in order for everything to work. Tho, i need the form to get filled as soon as the page loads.



What's goin on here? How can I fix this conundrum?










share|improve this question


















  • 1





    Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

    – penleychan
    Nov 28 '18 at 18:03











  • How can i make the page wait for the >this.user< to be resolved?

    – CH4B
    Nov 28 '18 at 18:05











  • You can either put it inside your subscribe or on its complete callback

    – penleychan
    Nov 28 '18 at 18:08














0












0








0








I have a form that i want to get filled with my database info.
In order to do that, i've made a method wich is called in my NgOnInit, but that method needs to be called twice in order to work.

This is the method:



  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]

})
};


The thing is, when the page loads, i get the following error in the console:




Cannot read property 'name' of undefined




But the weird thing is, if i make a button that calls getData(), when clicked, everything works fine. If i remove getData() from NgOnInit, I have to click twice the said button in order for everything to work. Tho, i need the form to get filled as soon as the page loads.



What's goin on here? How can I fix this conundrum?










share|improve this question














I have a form that i want to get filled with my database info.
In order to do that, i've made a method wich is called in my NgOnInit, but that method needs to be called twice in order to work.

This is the method:



  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]

})
};


The thing is, when the page loads, i get the following error in the console:




Cannot read property 'name' of undefined




But the weird thing is, if i make a button that calls getData(), when clicked, everything works fine. If i remove getData() from NgOnInit, I have to click twice the said button in order for everything to work. Tho, i need the form to get filled as soon as the page loads.



What's goin on here? How can I fix this conundrum?







angular forms






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 28 '18 at 18:00









CH4BCH4B

98111




98111








  • 1





    Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

    – penleychan
    Nov 28 '18 at 18:03











  • How can i make the page wait for the >this.user< to be resolved?

    – CH4B
    Nov 28 '18 at 18:05











  • You can either put it inside your subscribe or on its complete callback

    – penleychan
    Nov 28 '18 at 18:08














  • 1





    Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

    – penleychan
    Nov 28 '18 at 18:03











  • How can i make the page wait for the >this.user< to be resolved?

    – CH4B
    Nov 28 '18 at 18:05











  • You can either put it inside your subscribe or on its complete callback

    – penleychan
    Nov 28 '18 at 18:08








1




1





Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

– penleychan
Nov 28 '18 at 18:03





Because you are calling this this.getById(100).subscribe(x => this.User = x); here in async. The value of this.User is not resolved yet, thus this.User.name etc is undefined when you are trying to initialize your form.

– penleychan
Nov 28 '18 at 18:03













How can i make the page wait for the >this.user< to be resolved?

– CH4B
Nov 28 '18 at 18:05





How can i make the page wait for the >this.user< to be resolved?

– CH4B
Nov 28 '18 at 18:05













You can either put it inside your subscribe or on its complete callback

– penleychan
Nov 28 '18 at 18:08





You can either put it inside your subscribe or on its complete callback

– penleychan
Nov 28 '18 at 18:08












2 Answers
2






active

oldest

votes


















2














Subscribe is async, your rest of the code in getData() gets executed before the subscribe has finished.



Try to move the code inside the 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]

});

});


};





share|improve this answer































    2














    You get the error:




    Cannot read property 'name' of undefined




    Because the class variable User would not be defined until your subscription finishes, the code below the subscription block will not wait for the subscription to finish.



    Write all your logic under the Subscription of this.getById(100).



    You can make your getData() as:



    getData() {
    this.getById(100).subscribe(x => {
    this.user = x;
    this.typeForm.setValue(this.user)
    });
    }


    You don't need to explicitly set all the values inside the formControls, You can use setValue() on the FormGroup to add the values as the structure of returned data is same as that of your form.






    share|improve this answer


























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525471%2fangular-6-click-the-button-twice-in-order-to-work%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Subscribe is async, your rest of the code in getData() gets executed before the subscribe has finished.



      Try to move the code inside the 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]

      });

      });


      };





      share|improve this answer




























        2














        Subscribe is async, your rest of the code in getData() gets executed before the subscribe has finished.



        Try to move the code inside the 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]

        });

        });


        };





        share|improve this answer


























          2












          2








          2







          Subscribe is async, your rest of the code in getData() gets executed before the subscribe has finished.



          Try to move the code inside the 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]

          });

          });


          };





          share|improve this answer













          Subscribe is async, your rest of the code in getData() gets executed before the subscribe has finished.



          Try to move the code inside the 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]

          });

          });


          };






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 28 '18 at 18:06









          AragornAragorn

          2,56911430




          2,56911430

























              2














              You get the error:




              Cannot read property 'name' of undefined




              Because the class variable User would not be defined until your subscription finishes, the code below the subscription block will not wait for the subscription to finish.



              Write all your logic under the Subscription of this.getById(100).



              You can make your getData() as:



              getData() {
              this.getById(100).subscribe(x => {
              this.user = x;
              this.typeForm.setValue(this.user)
              });
              }


              You don't need to explicitly set all the values inside the formControls, You can use setValue() on the FormGroup to add the values as the structure of returned data is same as that of your form.






              share|improve this answer






























                2














                You get the error:




                Cannot read property 'name' of undefined




                Because the class variable User would not be defined until your subscription finishes, the code below the subscription block will not wait for the subscription to finish.



                Write all your logic under the Subscription of this.getById(100).



                You can make your getData() as:



                getData() {
                this.getById(100).subscribe(x => {
                this.user = x;
                this.typeForm.setValue(this.user)
                });
                }


                You don't need to explicitly set all the values inside the formControls, You can use setValue() on the FormGroup to add the values as the structure of returned data is same as that of your form.






                share|improve this answer




























                  2












                  2








                  2







                  You get the error:




                  Cannot read property 'name' of undefined




                  Because the class variable User would not be defined until your subscription finishes, the code below the subscription block will not wait for the subscription to finish.



                  Write all your logic under the Subscription of this.getById(100).



                  You can make your getData() as:



                  getData() {
                  this.getById(100).subscribe(x => {
                  this.user = x;
                  this.typeForm.setValue(this.user)
                  });
                  }


                  You don't need to explicitly set all the values inside the formControls, You can use setValue() on the FormGroup to add the values as the structure of returned data is same as that of your form.






                  share|improve this answer















                  You get the error:




                  Cannot read property 'name' of undefined




                  Because the class variable User would not be defined until your subscription finishes, the code below the subscription block will not wait for the subscription to finish.



                  Write all your logic under the Subscription of this.getById(100).



                  You can make your getData() as:



                  getData() {
                  this.getById(100).subscribe(x => {
                  this.user = x;
                  this.typeForm.setValue(this.user)
                  });
                  }


                  You don't need to explicitly set all the values inside the formControls, You can use setValue() on the FormGroup to add the values as the structure of returned data is same as that of your form.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 28 '18 at 18:16

























                  answered Nov 28 '18 at 18:08









                  xyzxyz

                  4,83021133




                  4,83021133






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525471%2fangular-6-click-the-button-twice-in-order-to-work%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                      Calculate evaluation metrics using cross_val_predict sklearn

                      Insert data from modal to MySQL (multiple modal on website)