首页 > 解决方案 > 无法在 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

这是我做的,一步一步:

import { AmplitudeClient } from 'amplitude-js';

[...]
@NgModule({
    [...]
    providers: [
        AmplitudeClient,
        [...]
    ]
});

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包不是我制作的,也没有导入我的任何提供者。

在此先感谢任何能给我指明正确方向的人!

标签: javascriptnode.jstypescriptionic3circular-dependency

解决方案


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


推荐阅读