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

时间:2018-10-23 22:01:33

标签: angular angular5

我正在尝试创建新对象并将其推送到数组。当我使用在方法中声明的局部数组localArr时有效,但是在使用类变量ERROR TypeError: Cannot read property 'blobList' of undefined时看到blobList: Azureblob[] = [];

enter image description here

 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;
   });
}

1 个答案:

答案 0 :(得分:1)

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

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

因为匿名函数中的this不引用您的类实例。它指的是正在调用该函数的对象。