Angular使用InjectionToken错误 [英] Angular using InjectionToken error

查看:86
本文介绍了Angular使用InjectionToken错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要使用 InjectionToken 注入值,但出现以下错误:

We need to inject a value using InjectionToken, but we are getting the following error:

在遇到错误时错误地静态解析符号值.由于此变量的值不正确,因此只能引用初始化变量和常量由模板编译器(原始.ts文件中的位置3:12)编辑,在C:/Projekte/Git/KWKPortal/App/src/app/shared/dnn.module.ts,resolvin中解析符号$g在C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts中的符号AppModule,在C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts中解析符号AppModule资源在C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts中的lving符号AppModule

ERROR in Error encountered resolving symbol values statically. Only initialized variables and constants can be referenced because the value of this variable is ne eded by the template compiler (position 3:12 in the original .ts file), resolving symbol $ in C:/Projekte/Git/KWKPortal/App/src/app/shared/dnn.module.ts, resolvin g symbol AppModule in C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts, resolving symbol AppModule in C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts, reso lving symbol AppModule in C:/Projekte/Git/KWKPortal/App/src/app/app.module.ts

这是我们提供要注入的值的方式:

here is how we provide this value to be injected:

import { SF, $, dnn } from './shared/dnn.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    { provide: SF, useValue: $.ServicesFramework(dnn.getVars().ModuleId) }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是我们的 dnn.module 的代码:

import { InjectionToken } from '@angular/core';

export let $: any;
export let dnn: any;
export let SF = new InjectionToken<any>('sf');

我想知道为什么会这样吗? useValue 是否不适用于这种情况?

I wonder why this is happening? Is useValue not proper for this case?

推荐答案

幸运的是,我能够使用工厂解决此问题,下面是代码:

Fortunally I was able to solve this using using factory, here is the code:

export function servicesFrameworkFactory() {
  return $.ServicesFramework(dnn.getVars().ModuleId);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [{
    provide: SF,
    useFactory: servicesFrameworkFactory,
    deps: []
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

我不知道是否有更干净的方法来解决此问题,但这解决了原来的问题.

I don't know if there is a cleaner way of fixing this, but this solved the original thread.

这篇关于Angular使用InjectionToken错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆