带有Angular 2的文件堆栈

时间:2017-04-17 21:19:14

标签: angular filepicker.io

我试图添加一个选项,在我的Angular 2 App中添加图像,并希望使用Filestack(以前的filepicker.io)来存储图像。 所以我将这些脚本标记包含在</body>上方的索引html文件中,正如Filestack建议的那样(并将我的API密钥放入)并在我的组件html中添加了<input>字段,该字段显示了添加新表单的表单配方:

index.html中的

<script src="https://static.filestackapi.com/v3/filestack-0.5.0.js"></script>
<script>
    var url = '';
    var client = filestack.init('myApiKey');
    function showPicker() {
        client.pick({
            maxFiles: 1
        }).then(function(result) {
            url = JSON.stringify(result.filesUploaded[0].url)
        });
    }
</script>

在recipe-form.component.html中:

<input type="button" value="Upload" onclick="showPicker()" />

现在效果非常好,它会上传图片,如果我添加console.log(url),它也会显示图片的网址。但是,似乎没有办法将该变量放入RecipeFormComponent,我想将url添加到我在那里创建的对象。我怎么能这样做?

我找到了很多关于如何在AngularJS中使用Filestack的内容,但是没有找到如何在Angular 2中使用它...

你知道有什么可以帮助我吗?

1 个答案:

答案 0 :(得分:4)

删除您为 index.html 显示的所有内容,但加载API的脚本标记除外。

<script src="//static.filestackapi.com/v3/filestack-0.5.0.js"></script>

然后更改您的组件以合并showPicker功能

<强>配方-form.component.ts

declare const filestack: {
  init(apiKey: string): {
    pick({ maxFiles }: { maxFiles: number }):
      Promise<{ filesUploaded: { url: string }[] }> 
  }
};

@Component({
  // boilerplate and ceremony
})
export class RecipeFormComponent {
  uploadedFileUrls: string[] = [];

  async showPicker() {
    const client = filestack.init('myApiKey');
    const result = await client.pick({ maxFiles: 1 });
    const url = result.filesUploaded[0].url;
    this.uploadedFileUrls.push(url);
  }
}

为了提高可维护性和可测试性,您应该将访问filestack全局的所有代码移动到专用服务中。

例如,我们可以编写像

这样的服务
// file-upload.service.ts
declare const filestack: {

  init(apiKey: string): {
    pick: (options: {maxFiles: number}) => Promise<{filesUploaded: {url: string}[]}>
  }
};

const client = filestack.init('myApiKey');

export default class {
  async uploadOne() {
    const result = await client.pick({ maxFiles: 1 });
    return {urls: result.filesUploaded.map(uploaded => uploaded.url)};
  }
}

我们可以使用包装API的服务从组件中使用它,并提供对我们的应用程序而言重要的结果

import FileUploadService from 'app/services/file-upload.service';

@Component({
  // boilerplate and ceremony
})
export class RecipeFormComponent {
  constructor(readonly fileUploadService: FileUploadService) {}

  uploadedFileUrls: string[] = [];

  async showPicker() {
    const {urls: [url]} = await this.fileUploadService.uploadOne();

    this.uploadedFileUrls.push(url);
  }
}

此外,如果您正在使用像SystemJS这样的模块加载器,那么最好删除脚本标记本身,通过加载器映射和隐藏其全局特性。