Sreekumar P
Sreekumar P

Reputation: 6050

How to pass optional arguments to callback functions in typescript

I have a callback function which returns some data to the component.

export class AppComponent {
  constructor(
    private service: AppService
  ) {
    this.processSomething(true);
    this.processSomething(false);
  }

  private processSomething(isZoom: boolean = false) {
    this.service.handleAsyncResponses(
      this,
      this.processDataReceived
    );
  }

  private processDataReceived(
    attributeValueList: any,
    isZoom?: boolean
  ) {
    console.log("isZoom:", isZoom);
  }
}

I need to send some value isZoom parameter from the component and access the same in console.log("isZoom:", isZoom). Now console.log is loggin undefined.

A working sample is here: https://stackblitz.com/edit/angular-service-oqkfmf?file=app/app.component.ts

Upvotes: 1

Views: 1937

Answers (2)

Noneme
Noneme

Reputation: 838

In your case, you need to wrap the function call in local closure:

private processSomething(isZoom: boolean = false) {
    this.service.handleAsyncResponses(
        this, (attributeValueList: any) => {
            this.processDataReceived(attributeValueList, isZoom);
        }
    );
}

changed example

Upvotes: 1

user4676340
user4676340

Reputation:

I think you're getting a little lost.

I took the freedom to clean your stackblitz from non-used code and show you how to use callbacks : you can check it there.

Let's start with the component :

constructor(
  private service: AppService
) {
  this.processSomething(true);
  this.processSomething(false);
}

private processSomething(isZoom: boolean = false) {
  this.service.handleAsyncResponses(isZoom, this.processDataReceived);
}

private processDataReceived(isZoom: boolean) {
  console.log("isZoom:", isZoom);
}

You don't need to define your parameters as optional, since you give your isZoom value a default value, hence making it always defined.

As you can see, you don't need to pass your full object as an argument : the function can be called without it.

In your service, all you have left is

public handleAsyncResponses(zoom: boolean, callback: Function) {
  callback(zoom);
}

Simply call the function as you would in any other context. simply rename this.processDataReceived(zoom) with the name of the parameter (here it being callback).

This is how callbacks are handled.

Upvotes: 2

Related Questions