1

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

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I cannot pass zoom as a param to handleAsyncReponses method, zoom is just a examples. It can varry based on components.
And since it is a parameter, you can make it vary. You offered a stackblitz, I used it as a base. If you want something more developped, then please provide a minimal reproducible example of it, so that I can explain it to you too.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.