0

I have a strange error. When I put layerinformation into a localvariable it works but when i try to put it in a variable which I want to use through my whole component it gives this error:

ERROR TypeError: Cannot read property 'setLayer' of undefined

This is my code:

 this.map.getLayers().forEach(function(layer, i) {
          if (layer instanceof Group) {

              var layerinfo = layer.getLayers();

          }
        });

The code above works fine but when I change var layerinfo into this.setLayer I get the TypeError can someone explain me why?

Thx!

Hans
  • 103
  • 1
  • 13

2 Answers2

1

Just Use Arrow function

this.map.getLayers().forEach((layer, i) => {
  if (layer instanceof Group) {
      var layerinfo = layer.getLayers();
  }
});
baj9032
  • 1,912
  • 1
  • 15
  • 35
  • what is the difference between a normal function and a arrowfunction – Hans Jun 13 '18 at 12:52
  • Just go throw https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch. – baj9032 Jun 13 '18 at 12:53
1

You need to use arrow functions. If you use function like that, the scope of your this is limited in your function only.

Traditional function

 public myTest:string = "mytest";
 (....)
 this.map.getLayers().forEach(function(layer, i) {
          if (layer instanceof Group) {

              var layerinfo = layer.getLayers();
              console.log(this.myTest);
          }
        });

So in this example, this is undefined because we can access on this of your component (scope limited in the function, only!)

Arrow functions

public myTest:string = "mytest";
 (....)
 this.map.getLayers().forEach((layer, i) => {
          if (layer instanceof Group) {

              var layerinfo = layer.getLayers();
              console.log(this.myTest);
          }
        });

In this second example, you can show the result of this.myTest (mytest). Because this of you component is available in arrow function.

Your case

So in your case :

public setLayer(){
    (...)
}
this.map.getLayers().forEach((layer, i) => {
  if (layer instanceof Group) {
      var layerinfo = layer.getLayers();
      this.setLayer();
  }
});

If you want more informations about that

Pterrat
  • 1,168
  • 8
  • 16