尝试将值添加到 Angular 中的 class 数组变量时出错 5

Error when trying to add values to a class array variable in Angular 5

我正在尝试创建新对象并将它们推送到一个数组中。当我使用在方法中声明的本地数组 localArr 但在使用 class 变量 blobList: Azureblob[] = [];.

时看到 ERROR TypeError: Cannot read property 'blobList' of undefined 时这有效

 import { Azureblob } from '../models/azureblob';

 export class BlobService {

   blobList: Azureblob[] = [];

   getAllBlobsJS(): Azureblob[] {
      //var localArr = new Array;

      this.blobServiceObj = AzureStorageBlobServiceJS.createBlobService(this.connectionString);

      this.blobServiceObj.listBlobsSegmented('acsazurecontainer', null, function (error, results) {
        if (error) {
          //console.log("**** Error");
        } else {
          for (var i = 0, blob; blob = results.entries[i]; i++) {
            //console.log("**** Success", blob);
            //localArr.push(blob.name);
            this.blobList.push(new Azureblob(blob.name));
        }
     }
     //console.log("**** localArr - Number of blobs returned=", localArr.length);
     console.log("**** Class Arr - blobList length=", this.blobList.length);
     return this.blobList;
   });
}

从局部变量引用您的数组然后使用它:

var localArr = this.blobList;
[...]
localArr.push(blob.name);

因为您的匿名函数中的 this 没有引用您的 class 实例。它指的是函数被调用的对象。