0

Using Angular's Dynamic forms I'm building a new input field

form.ts

 usernameCallback(body) {
    console.log(`hello ${body}`);
    this.usernameService.post(body)
       .subscribe(
         data => {
           console.log(data);
         },
         error => {
           console.warn(`Error: ${error}`);
         }
       );
  }

ngOnInit() {

      new InputField({
        key: 'username',
        label: 'Username',
        value: '',
        placeholder: 'Enter username',
        required: true,
        callback: this.usernameCallback
      }),

}

So this is the basics of the code.

I have inside UsernameService a method post() which sends an http post request.

usernameCallback() is added to the InputField and has the type of Function to it.

Within input.component.ts where the form is built I am doing

  callback() {
    console.log(this.field.callback);
    this.field.callback('cheddar');
  }

The console log prints out the content from usernameCallback which is fine but I get an error

ERROR TypeError: Cannot read property 'post' of undefined

It looks like it isn't able to process the usernameService but I cannot figure out why.

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
  • 1
    `this.usernameCallback.bind(this)` should do the trick – yurzui Nov 22 '18 at 18:01
  • Alternatively you can use instance arrow function like `usernameCallback = (body) => {` More on this you can find everywhere:) https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript – yurzui Nov 22 '18 at 18:03
  • Where should `this.usernameCallback.bind(this)` be places @yurzui –  Nov 22 '18 at 18:07
  • `callback: this.usernameCallback.bind(this)` – yurzui Nov 22 '18 at 18:18
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Nov 22 '18 at 18:49

0 Answers0