javascript - 无法在 Ionic 3 应用程序中导入 Amplitude SDK
问题描述
我正在尝试使用 Amplitude SDK 从我的 Ionic 3 应用程序中获取统计信息。但是,由于该应用程序是用 TypeScript 编写的,具有一定的文件架构,因此并不像官方文档中描述的那么简单。
但是,我找到了 @types/amplitude-js 包,我认为它可以解决我的所有问题。但不幸的是,当我在我的设备上使用 编译我的应用程序时ionic cordova run android --device
,该应用程序没有加载并且我收到以下错误消息:
Uncaught Error: Encountered undefined provider!
Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
注意:我运行时也会出现此错误ionic serve
。
这是我做的,一步一步:
- 我通过运行安装了@types/amplitude-js
npm install --save @types/amplitude-js
。 - 我通过运行
npm install amplitude-js
. 我注意到有必要这样做,否则我的应用程序不会仅使用 @type 包进行编译(这是有道理的)。 - 我将以下行添加到我的
app.module.ts
import { AmplitudeClient } from 'amplitude-js';
[...]
@NgModule({
[...]
providers: [
AmplitudeClient,
[...]
]
});
- 我还创建了一个
AmplitudeProvider
,它将管理整个应用程序中的所有 Amplitude 事件:
import { Injectable } from '@angular/core';
import { HttpServiceProvider } from "../http-service/http-service";
import { AmplitudeClient } from 'amplitude-js';
/**
* AmplitudeProvider
* @description Handles Amplitude statistics
*/
@Injectable()
export class AmplitudeProvider {
constructor(
public http: HttpServiceProvider,
public amplitude: AmplitudeClient
) {
this.amplitude.init("MY_AMPLITUDE_KEY");
}
/**
* logEvent
* @description Logs an event in Amplitude
* @param eventTitle Title of the event
*/
public logEvent(title) {
// Do things not relevant here
}
}
我确定我的依赖注入和/或导入有问题,但我不明白是什么。而且我没有看到任何循环依赖,因为amplitude-js
包不是我制作的,也没有导入我的任何提供者。
在此先感谢任何能给我指明正确方向的人!
解决方案
AmplitudeClient 不是 Ionic Provider,因此,您不能将其导入并放入您的 Class 构造函数中。
要在您的 Provider 中使用幅度,您需要导入幅度。您的代码应该与此类似。
import amplitude, { AmplitudeClient } from 'amplitude-js';
@Injectable()
export class AmplitudeProvider {
private client: AmplitudeClient;
constructor(
public http: HttpServiceProvider,
public database: DatabaseProvider
) {
this.client = amplitude.getInstance();
this.client.init("MY_AMPLITUDE_KEY");
}
}
推荐阅读
- python - Python win32com excel工作表
- image - 如何右对齐 PictureBox 中的图像
- javascript - 根据用户角色限制点击按钮
- jupyter-notebook - FileUpload ipywidget:如何指定初始目录?
- python - 我不断收到此错误代码,但不知道为什么?只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或
- python - python文件转换为exe上升错误
- groovy - 在 Groovy 中 - 如何比较major.minor.patch 和major minor 的版本?
- go - 调试单个测试时如何提供测试标志?
- php - 使用 $_session 存储具有从 api 检索到的动态数据的变量,以 json 格式在不同的页面中使用
- java - android studio getDownloadUrl() 解析