【问题标题】:How to return data of Promise then in angular 2然后如何以角度2返回Promise的数据
【发布时间】:2019-02-23 07:57:36
【问题描述】:

我正在使用文件堆栈来上传文件。我只想创建一个上传服务,以便我可以在任何组件中重用。但是我的代码有问题。

这是服务文件中的一个函数

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

我在组件中的调用函数

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

我在服务功能中得到响应,但在组件中没有。问题出在哪里,并提出一种方法来完成在组件中重用该功能

【问题讨论】:

    标签: angular angular2-services angular2-components filestack


    【解决方案1】:

    函数 fsClient.pick() 似乎返回了一个 Promise,因此不要将调用 fsClient.pick(fileOptions) 包装在另一个 Promise 中,您可以只从 uploadFiles 函数返回这个调用。所以只需返回 fsClient.pick(fileOptions)。组件中的代码保持不变。

    【讨论】:

    • 我尝试返回 fsClient.pick(fileOptions),仍然没有在 then 函数中得到响应
    • 相当奇怪。此代码放在组件中的什么位置: this._fs.uploadFiles() ?它在生命周期钩子内吗?
    • @Manush 你也可以发布你的最后一次尝试吗?
    猜你喜欢
    • 2017-01-10
    • 2023-03-09
    • 2018-07-05
    • 2017-02-21
    • 2016-07-26
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多