如何在角度2中同步两个onloadend函数?

时间:2017-09-01 09:42:55

标签: angular

我是Angular 2/4的新手,我已经到了一个可以从本地目录中读取多个文件的地方。在我的函数中,数据(来自每个文件)被解析并推送到2个不同的数组中但是在onloadend函数之后我无法访问数组数据,我想这是一个同步问题。

我的代码:

changeListener($event: any) {
       this.readFile($event.target);
    }
readFile(input: any) {
  var self = this;
  var files : File [] = input.files;
  var employeeSet : Employee [] = new Array<Employee>();
  var serviceSet : Service [] = new Array<Service>();
  for (let i=0; i < files.length; i++) {
            console.log(files[i].name);

            if (files[i].name == 'employees') {
              var employeeReader : FileReader = new FileReader();
              employeeReader.readAsText(files[i]);

              employeeReader.onload = function(e) {
              var alldata = employeeReader.result;
              var allTextlines = alldata.split(/\r?\n/);

              for (var i=0; i < allTextlines.length; i++) {
                var columns = allTextlines[i].split('|');
                var employee : Employee = new Employee();
                if (columns[0] != '') {
                  employee.id = Number(columns[0]);
                  employee.firstName = columns[1];
                  employee.lastName = columns[2];
                  employee.jobPosition = columns[3];
                  employee.status = columns[4];
                  employee.company.name = columns[5];
                  employee.mobilePhone = columns[6];
                  employee.iternalNumber = columns[7];
                  employee.email = columns[8];
                  employee.hireDate = columns[9];
                  var totalServices = columns[10].split(',');
                  for (var j = 0; j < totalServices.length; j++) {
                    var serviceDescr = totalServices[j];
                    employee.services.push(serviceDescr);
                  }

                  employeeSet.push(employee);



                }
                // self.apiServ.addUser(user).subscribe(
                //   (data) => {
                //     if( data instanceof Observable) {
                //       data.subscribe(
                //         (f) => {console.log(f);
                //         });
                //     }
                //   }
                // );
              }
              console.log(employeeSet);
              self.complete.next(employeeSet);
              // console.log('Tha steiloume ston server to akoloutho array: \n', resultSet);
            };
          } else if(files[i].name == 'services') {

            var serviceReader : FileReader =  new FileReader();
            serviceReader.readAsText(files[i]);

            serviceReader.onload = function(e) {
            var alldata = serviceReader.result;
            var allTextlines = alldata.split(/\r?\n/);
            for (var i=0; i < allTextlines.length; i++) {
              var columns = allTextlines[i].split('|');
              var service : Service = new Service();
              if (columns[0] != '') {
                service.id = Number(columns[0]);
                service.description = columns[1];
                service.price = columns[2];
                service.cost = columns[3];

                serviceSet.push(service);


              }
            }
            console.log(serviceSet);
            self.complete.next(serviceSet);
          };



  }




}



// Here I want to access the data but i cant. 




}

有任何帮助吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

我实现了与Promises类似的工作(它仍然是异步但以更好的方式处理它)。您应该能够在then方法中使用数组。

ImageHelper.ts

export class ImageInfo {

  name: string;
  size: number;
  width: number;
  height: number;

}

export class ImageHelper {

  static getImageInfo(image: File): Promise<ImageInfo> {

    const imageInfo: ImageInfo = new ImageInfo();

    return new Promise<ImageInfo>((resolve, reject) => {

      try {

        imageInfo.name = image.name;
        imageInfo.size = image.size;

        const reader = new FileReader();

        reader.onloadend = (onLoadEvent) => {

          const imageAux = new Image();
          imageAux.src = reader.result;

          imageAux.onload = function () {

            imageInfo.width = imageAux.width;
            imageInfo.height = imageAux.height;

            resolve(imageInfo);
          };
        };
        reader.readAsDataURL(image);
      } catch (error) {

        reject(error);
      }
    });
  }

}

无论在哪里。

principalUpload(event) {

  ImageHelper.getImageInfo(event.target.files[0])
    .then((imageInfo: ImageInfo) => console.log(imageInfo));
  ...
}

我希望这能帮到更多人。