0

I want to use a service object in callback method. I get undefined error when I use the service in callback method. How can I solve it?

send.component.ts

import { Component } from '@angular/core';

import { ExampleService } from '../../services/example.service';

@Component({
  selector: 'example',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent {
  public exampleService = null

  constructor(private service: ExampleService) {
    this.exampleService = service
  }

  submit() {
    function postSendTransactionCallback(result) {
      console.log(this.exampleService); // exampleService is undefined
    }

    this.exampleService.postSendTransaction(this.data, postSendTransactionCallback); // This is no problem
  }
}
zono
  • 8,366
  • 21
  • 75
  • 113

2 Answers2

1

Use Arrow function while defining postSendTransactionCallback

submit() {
    let postSendTransactionCallback = (result) => {
      console.log(this.exampleService);
    }
    this.exampleService.postSendTransaction(this.data, postSendTransactionCallback);
}

Use .bind(this) like below without changing postSendTransaction method

this.exampleService.postSendTransaction(
  this.data, postSendTransactionCallback.bind(this)
);
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
1

User arrow function because javascript arrow(=>) function bind the scope with it where it is defined:

 submit() {
    this.exampleService.postSendTransaction(this.data, (result) => {
      console.log(this.exampleService); // 
    }); 
  }
asmmahmud
  • 4,844
  • 2
  • 40
  • 47