0

I have the following code:

component.ts:

this.EnumField = Enum.val0;
this.OperationResult = "";


onClick(): any{
  this.EnumFiled = Enum.val1;
  this.service.func(this.param, this.successCallback, this.successCallback)
}

successCallback(res: string): void{
  this.EnumField = Enum.val2;
  this.OperationResult = res;
}

service.ts:

func(param: string, successFn: any, errorFn: any) {
  let url = '/some_url'
  let params = {'param': param};
  this.http.get(url, {params:params})
    .subscribe(
       (res) => {
            console.log(res.toString());
            successFn(res.toString());
        },
        error => {
            console.log(error.toString());
            errorFn(error.toString());
        }
    );
}

The code works fine, and is able to connect to the server and retrieve results, but when I get back from within the subscribe to the component the "this" is not recognized and I cannot update the value of the Enum. I believe it has something to do with the context but I can't seem to find the right syntax. Can you tell me how to get back my context upon return?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Orit
  • 314
  • 2
  • 6
  • Also, another point: you're going back from observables to callback recipe. It is a bad idea, and a straight road to callback hell. Let the service return an observable (if you want to `console.log`, just add a `tap` operator in the pipe), and the component subscribe it. – mbojko Sep 08 '22 at 13:39
  • @mbojko I thought of doing that, however, I have more than one call to the service and I will have to address the success and failure of the observable in each function separately and I prefer to avoid that if I can. – Orit Sep 08 '22 at 14:25

0 Answers0