Angular - How to set the value inside the function?

匆匆过客 提交于 2021-02-11 12:50:45

问题


I am not able to set the this.isHiddenColumnAvail value. How to set this value?

checkHiddenRowAndColumns(file) {
    const workbook = new Excel.Workbook();
    const arryBuffer = new Response(file).arrayBuffer();
    arryBuffer.then(function (data) {
      workbook.xlsx.load(data)
        .then(function () {
          const worksheet = workbook.getWorksheet(1);

          //check hidden columns
          for(var i=0; i < worksheet.columns.length; i++) {
            if(worksheet.columns[i].hidden == true){
              this.isHiddenColumnAvail = true;
              break;
            }
          }

          //check hidden rows
          worksheet.eachRow(function (row,rowNumber) {
            if(row.hidden == true) {
              this.isHiddenColumnAvail = true;
            }
          });
        });
    });
  }

回答1:


It's simple you need to change the function to an arrow function.

Using Arrow functions you can use this, allowing you access outside/global variables.

See the example bellow:

      worksheet.eachRow((row,rowNumber) => {
        if(row.hidden == true) {
          this.isHiddenColumnAvail = true;
        }
      });

In your code, replace the other functions with arrow functions

Observations:

  • Arrow functions are allowed in es6 or more than

Reference:

  • https://medium.com/better-programming/difference-between-regular-functions-and-arrow-functions-f65639aba256
  • https://262.ecma-international.org/6.0/#sec-arrow-function-definitions


来源:https://stackoverflow.com/questions/66045243/angular-how-to-set-the-value-inside-the-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!