无法读取未定义的属性'service'

问题描述 投票:0回答:2

即使我总是以这种方式访问​​我拥有的其他脚本,我也不知道为什么无法访问或找到该服务。

[首先,我注入服务,该服务包含将客户添加到数据库并尝试从深层两个for循环和一个if语句访问它的功能。甚至注入的消防站也无法访问。我不知道为什么,也不知道。你们可以帮我吗?

 constructor(
    public service: CustomerService,
    public firestore: AngularFirestore,
    ) { }



    scanImage() {
    console.log('>>>> Customer Scanning Image...');
    // let data: Customer;
    // this loops thru available pictures
    for (let image = 0; image < this.images.length; image++) {
      Tesseract.recognize (this.images[image]).then(
        function(result) {

        // store scanned text by new line
        const newLine = result.text.split('\n');

        // loop thru line
        for (let line = 0; line < newLine.length; line++) {

          // store scanned text by word
          const word = newLine[line].split(' ');


          // ask if we find the customer lines in the picture
          if (word[word.length - 1] === '>') {
            console.log(`>>>> time: ${word[0]}`);
            console.log(`>>>> code: ${word[1]}`);
            console.log(`>>>> name: ${word[2] + ' ' + word[word.length - 4]}`);
            console.log(`>>>> total: ${word[word.length - 3]}`);
            console.log(`>>>> status: ${word[word.length - 2]}`);
            console.log('______________________\n');

            const data: Customer = {
              time: word[0],
              code: word[1],
              name: word[2] + ' ' + word[word.length - 3],
              total: word[word.length - 2],
              status: word[word.length - 1]
            };

            this.service.add(data);
            // this.sendCustomer(data);

            // this.firestore.collection('customers').add(data);
            // this.customerList.push(data);

          }
        }
      });
    }
  }
angular typescript
2个回答
1
投票

问题是您的function(result) {...}功能。通过在其中执行代码,您可以创建一个新的作用域,this现在引用该function

相反,使用箭头函数保留类的范围。

显示此行为的示例:

class Test {
    withArrowFunction() {
        (() => console.log(this))();
    }

    withNormalFunction() {
        (function() {
            console.log(this);
        } )();
    }
}

const test = new Test();
test.withArrowFunction();
test.withNormalFunction();

如您所见,箭头功能可以访问在普通功能的thisundefined时实例化的实际对象。


0
投票

尝试使用Arrow function expressions。箭头功能没有自己的this。使用封闭词法范围的this值;

Tesseract.recognize (this.images[image]).then(
    (result) => {
        // this reference will atachto class
    }
)
© www.soinside.com 2019 - 2024. All rights reserved.