Angular 2 的文件堆栈

Filestack with Angular 2

我正在尝试添加一个选项以在我的 Angular 2 应用程序中添加图像,并且想使用 Filestack(以前的 filepicker.io)来存储图像。 因此,我按照 Filestack 的建议将这些脚本标签包含在 </body> 上方的索引 html 文件中(并将我的 API 键放入)并在我的组件中添加了 <input> 字段 html 显示用于添加新配方的表单:

在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>

食谱中-form.component.html:

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

现在一切正常,它会上传图像,如果我添加 console.log(url),它还会显示图像的 url。但是,似乎无法将该变量放入我想将 url 添加到我在那里创建的对象的 RecipeFormComponent 中。我怎么能那样做?

我发现了很多关于如何将 Filestack 与 AngularJS 一起使用的内容,但在 Angular 2...

中找不到如何执行此操作的内容

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

删除为 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 这样的模块加载器,您最好删除脚本标签本身,通过加载器映射和隐藏它的全局特性。