How to return data of Promise then in angular 2

183 Views Asked by At

I'm using filestack for uploading files. I just want to create a service for uploading so that I can reuse in any components. But I have a problem with my code.

This is a function in the service file

uploadFiles(file,size) {
    let fsClient = filestack.init(fsKey);
    let fileAccepted = file;
    let maxSize = size;
    let fileOptions = {
      fromSources:["local_file_system"],
      accept: fileAccepted,
      maxFiles:1,
      minFiles:1,
      transformations:{
        crop:true,
        circle:false
      },
      maxSize:maxSize
    };
    let fileRes = new Promise((resolve, reject) => {
      fsClient.pick(fileOptions).then((response) => {
        if(response) {
          console.log(response);
          resolve(response);
        } else {
          reject();
        }
      });
    });
    return fileRes;
  }

My Calling function in component

this._fs.uploadFiles(fileAccepted,maxSize).then((response) => {
        console.log(response);
});

I get the response in service function, but not in the component. Where is the problem and suggest a way to accomplish to reuse the function in components

1

There are 1 best solutions below

3
Avinash Lahel On

The function fsClient.pick() seems to return a promise, so instead of wrapping the call fsClient.pick(fileOptions) inside another promise, you could just return this call from the uploadFiles function. So just return fsClient.pick(fileOptions). The code in the component remains unchanged.