Angular 2 OpaqueToken

标签 angular

在提供 OpaqueToken 方面需要一些帮助。使用 Angular 2 beta-12。如果 provider key 是一个字符串,它工作正常,但在使用 OpaqueToken 时不起作用。在 Child 类中,SF 是未定义的。

父类:

export let SF = new OpaqueToken('sf');

export class A {
  testMsg: string = 'hello';
}

@Component({
  template: `<child></child>`,
  providers: [
    provide(SF, {useValue: A}),
    provide('justString', {useValue: 'hi'}) 
  ]
})
export class App {}

子类:

import {Component, Injector, Inject, OpaqueToken} from 'angular2/core'
import {SF, A} from './app'
console.log("******", SF); // undefined
@Component({
  selector: 'child',
  template: `
    $$CHILD Rendered$$ {{a}}
  `
})
export class Child {
  //constructor(@Inject(SF) private a: A) {} // doesn't work
  constructor(@Inject('justString') private a: string) {}
}

我得到的异常:

angular2.min.js:17EXCEPTION: Cannot resolve all parameters for 'Child'(@Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Child' is decorated with Injectable.

最佳答案

这是因为您在包含父类和子类的模块之间存在循环依赖。

如果您将不透明 token 定义到第三个模块并将其包含在其他模块中,它将起作用。

例如常量模块:

export let SF = new OpaqueToken('sf');

在另外两个模块中:

import { SF } from './constants';

关于 Angular 2 OpaqueToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436005/

相关文章:

angular - 检查用户是否登录 Angular 2 中的任何页面更改

java - 如何在 TypeScript 中定义结构?

javascript - 表中的行计数器

Angular 6 和 Electron : Using a mocked class for unit testing and extend the real class does not work

javascript - Angular - 是否可以通过指令阻止执行(点击)事件?

javascript - angular2 路由守卫验证

node.js - NG Build 在 Azure Pipelines 中失败,出现 NPM 错误 134

node.js - 如何在angular 2项目中使用 "regression-js"

javascript - 指令在应用程序中不起作用

angular - angular i18n 应用程序的 Nginx 配置