0

I have typescript project and more specific and Angular application.

I have my Class called Test (you can assume its a component in angular) and it has access to http service which is usually used like this.http('/endpoint').subscribe(response => {});

I need to add some logic in between and break it down into separate methods (the code is a little bit more complicated than in my example).

export class Test {

init() {
    this.http.get('/endpoint').map(this.transform);
}

transform(data) {
    // more logic here in isolated scope

    this.accessOutside(data); // I cannot access this method, isolated scope.
    // How to break down some logic into separate methods to access them
    // or how to create it new method within method?

    return data
}

accessOutside(data) {
    // more logic
}

}

When i call this.http.get('/endpoint').map(this.transform) my "transform" method is isolated and has no access to other methods within Test class, but how to access it or how to create method within transform method?

TroodoN-Mike
  • 15,687
  • 15
  • 55
  • 78

1 Answers1

1

When you pass the transform function into the map function like this

this.http.get('/endpoint').map(this.transform);

you are passing a copy of the transform function, which has no concept of this. As a result, when the map function calls the copy of the transform function, it's context will default to the window object. So in the copy of the transform method, it will be looking for a function called accessOutside on the window object.

The simplest way to fix this problem is to use a lambda function as follows:

this.http.get('/endpoint').map(data => this.transform(data));

As arrow funcitons have access to the scope of the context they are defined in, when map calls the arrow function, this will refer to your instance of Test and not window

Nicholas Robinson
  • 1,359
  • 1
  • 9
  • 20