【问题标题】:Angular Compiler throws Internal error: unknown identifier {}Angular 编译器抛出内部错误:未知标识符 {}
【发布时间】:2017-10-06 15:33:28
【问题描述】:

我正在像这样构建我的 angular2 服务

import { OpaqueToken, ClassProvider } from "@angular/core";

export interface IService {
  // ... interface declaration
}

export class Service implements IService {
  // ... implementation goes here
}

export const IService = new OpaqueToken(Service.name);

export const ServiceProvider: ClassProvider = {
    provide: IService,
    useClass: Service,
};

使用 ngc 和 angular 2.x.x 可以很好地工作和编译 但是在升级到 Angular 4.x.x 后,ServiceProvider 在组件“提供者”数组中使用时不能再进行 ngc 编译。 (有趣的是,当提供程序注册在 ngModule 中而不是在组件中时,整个事情都有效。)

我在控制台上得到以下信息:

events.js:160 投掷者; // 未处理的“错误”事件 ^ 错误:命令失败:npm run ngc 错误:内部错误:未知标识符 {}

有什么想法吗?我可能会将我的服务转换为 @Injectable() 并且不使用该接口,但这似乎与使用服务接口的整个想法背道而驰:(

仅供参考:我使用的是 TypeScript 2.2.2

非常感谢您的帮助!

【问题讨论】:

    标签: angular typescript angular-compiler-cli


    【解决方案1】:

    https://angular.io/docs/ts/latest/api/core/index/OpaqueToken-class.html

    OpaqueToken 在 4.x 中已被弃用,不妨尝试使用 InjectionToken 代替。

    这是我想到的第一件事。

    【讨论】:

    • 非常感谢。我会尽快尝试并通知您。
    【解决方案2】:

    很遗憾,将 OpaqueToken 替换为 InjectionToken 并没有解决问题。 但是,使用抽象类而不是接口和注入令牌。

    根据这个答案Angular 2 Injectable Interface?,注入抽象类并像接口一样使用它们是一个常见的配方(也被角度团队本身使用)。

    import { ClassProvider } from "@angular/core";
    
    export abstract class IService {
      // ... interface declaration
    }
    
    export class Service implements IService {
      // ... implementation goes here
    }
    
    export const ServiceProvider: ClassProvider = {
        provide: IService,
        useClass: Service,
    };

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2016-12-15
      • 2014-01-05
      • 2023-03-16
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多