简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM