You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Capacitor 5迁移后@awesome-cordova-plugins/file注入错误求助

问题描述

迁移至Capacitor 5并更新Cordova相关包后,使用@awesome-cordova-plugins的File和FileTransfer组件时持续出现[object Object]注入错误。

当前代码配置:

  1. 导入语句:
import { FileTransfer, FileTransferObject } from '@awesome-cordova-plugins/file-transfer/ngx';
import { File } from '@awesome-cordova-plugins/file/ngx';
  1. NgModule的providers配置:
@NgModule({
...
providers: [FileTransferObject,File],
...
})

遇到的错误:

  • 初始配置时出现:
ERROR Error: Uncaught (in promise): NullInjectorError: 
R3InjectorError(PdfViewerPageModule)
[[object Object] -> [object Object] -> [object Object] -> [object Object] -> [object Object]]: 
NullInjectorError: No provider for [object Object]!
  • 添加FileTransferObject到providers后出现:
ERROR Error: Uncaught (in promise): Error: Invalid provider for the NgModule 
'PdfViewerPageModule' - 
only instances of Provider and Type are allowed, got: 
[..., ..., ?[object Object]?]

经排查问题源于private transfer: FileTransfer的注入,尝试添加FileTransfer到providers仍提示无效提供者错误。

解决方案

1. 修正NgModule的Providers配置

FileTransferObject不是可直接注入的服务类型,不要将其添加到providers数组中。正确的做法是只在providers中声明FileTransfer和File:

@NgModule({
  ...
  providers: [FileTransfer, File],
  ...
})
export class PdfViewerPageModule { }

2. 组件中正确使用FileTransferObject

在组件中,通过FileTransfer的create()方法来获取FileTransferObject实例,而不是直接注入FileTransferObject:

import { Component } from '@angular/core';
import { FileTransfer, FileTransferObject } from '@awesome-cordova-plugins/file-transfer/ngx';
import { File } from '@awesome-cordova-plugins/file/ngx';

@Component({
  selector: 'app-pdf-viewer',
  templateUrl: './pdf-viewer.page.html',
  styleUrls: ['./pdf-viewer.page.scss'],
})
export class PdfViewerPage {
  private transferObject: FileTransferObject;

  constructor(private transfer: FileTransfer, private file: File) {
    // 创建FileTransferObject实例
    this.transferObject = this.transfer.create();
  }

  // 示例:使用transferObject执行下载
  downloadFile() {
    const url = 'https://example.com/file.pdf';
    const filePath = this.file.dataDirectory + 'downloaded.pdf';

    this.transferObject.download(url, filePath).then((entry) => {
      console.log('下载完成: ' + entry.toURL());
    }, (error) => {
      console.error('下载失败: ', error);
    });
  }
}

3. 验证Capacitor与插件兼容性

确保@awesome-cordova-plugins/file、@awesome-cordova-plugins/file-transfer的版本与Capacitor 5兼容,建议安装最新适配版本:

npm install @awesome-cordova-plugins/file@latest @awesome-cordova-plugins/file-transfer@latest

4. 检查Cordova插件依赖

FileTransfer依赖Cordova的cordova-plugin-file-transfer插件,确保已正确安装:

npm install cordova-plugin-file-transfer
npx cap sync

内容的提问来源于stack exchange,提问作者Steven Putra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:22:07