3

I want to lazy load data for cacader. But failed because in the load function this=undefined. The function is defined in component, and other functions in the component working well. Please help, thanks.

<nz-cascader  
  \[nzLoadData\]\="loadCityBuildingData"  
  \[(ngModel)\]\="selectedLocation"  
  (ngModelChange)\="onNewLocationModalChanges($event)"  
\> </nz-cascader>
loadCityBuildingData(node: NzCascaderOption, index: number): PromiseLike<void\> {  
  console.log(this);  

 return new Promise(resolve => {  
    if (index < 0) {  
      this.cityService.getCities().subscribe(item => {  
        const cities = \[\];  
  item.forEach(city => {  
          cities.push({value: city.id, label: city.name});  
  });  
  node.children \= cities;  
  resolve();  
  });  
  } else if (index === 0) {  
      this.buildingService.getBuildingsByCityId(node.value).subscribe(item => {  
        const buildings = \[\];  
  item.forEach(building => {  
          buildings.push({value: building.id, label: building.name, isLeaf: true});  
  });  
  node.children \= buildings;  
  resolve();  
  });  
  }  
  });  
}
Pedro Mutter
  • 1,178
  • 1
  • 13
  • 18
ZhaoGuoXin
  • 43
  • 2

2 Answers2

2

A solution I found that works for me is to define your function like following :

loadCityBuildingData = (node: NzCascaderOption, index: number): PromiseLike<void> => {
    ...your code 
}
2

My name's Wendell and I am the author of the component. ;)

This is a frequestly asked question. The reason is that:

  1. When you pass loadCityBuildingData to nzLoadData, loadCityBuildData becomes a property of NzCascaderComponent.
  2. When the cascader calls this method (by calling nzLoadData actually), this in loadCityBuildingData is bound to nothing.
  3. So you have to bind this in loadCityBuildingData before you pass it.
    1. You could use arrow function.
    2. You could use Function.bind.
hullis
  • 350
  • 2
  • 13