注入令牌在服务中未定义,但在组件中找到

时间:2019-03-27 12:14:31

标签: angular typescript dependency-injection

我正在将外部js库作为InjectionTokens添加到Angular 7应用程序,以便在@Components和服务中使用它们。 我创建了接口InjectionToken<>Provider,并将Provider添加到providers: []的{​​{1}}属性中。

我一直关注this guide,介绍如何注入第三方库。

@NgModule注入组件时,可以很好地使用它。当我尝试将其注入服务时,出现InjectionToken错误。

... is not defined

angular.json

[...] "scripts": [ "./node_modules/hot-formula-parser/dist/formula-parser.js", "./node_modules/@handsontable/formulajs/dist/formula.js" ] [...]

entry.module.ts

import { NgModule, InjectionToken } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EntryComponent } from './entry.component'; import { RouterModule } from '@angular/router'; import { entryRoutes } from './entry.routes'; import { SharedModule } from 'src/shared/shared.module'; import { EntryService } from './entry.service'; import { HotParserProvider} from './parser/parser.injector'; @NgModule({ declarations: [EntryComponent], imports: [SharedModule, CommonModule, RouterModule.forChild(entryRoutes)], exports: [], providers: [ HotParserProvider, EntryService, ], }) export class EntryModule { }

parser.injector.ts

import { InjectionToken, ValueProvider } from "@angular/core"; interface IHotParser { parse: (formula: string) => {error:string, result: any}; } const HotParser: InjectionToken<IHotParser> = new InjectionToken<IHotParser>('HotParser'); const HotParserProvider: ValueProvider = { provide: HotParser, useValue: new window['formulaParser'].Parser() } export {IHotParser, HotParser, HotParserProvider};

entry.component.ts

import { Component, Inject } from '@angular/core'; import { EntryService } from './entry.service'; import { HotParser, IHotParser } from './parser/parser.injector'; @Component({ selector: 'tp-entry', templateUrl: './entry.component.html', styleUrls: ['./entry.component.css'] }) export class EntryComponent { constructor( @Inject(HotParser) private parser: IHotParser, // No error! private entryService:EntryService ) { } ngOnInit(): void { console.log(parser.parse("SUM(1,1)"); // Correct output! } }

entry.service.ts

在组件和服务中注入令牌之间有区别吗? 我试图更改模块提供者数组的顺序,但无济于事...

1 个答案:

答案 0 :(得分:1)

没关系。 Visual Studio代码的提示没有警告我HotParser尚未导入服务的import语句中……我看到以下编译器错误:

ERROR in src/entry/entry.service.ts(11,25): error TS2304: Cannot find name 'HotParser'.

所以最终改变了:

import { IHotParser } from './parser/parser.injector';

至:

import { HotParser, IHotParser } from './parser/parser.injector';

错误消失了。