![](/img/trans.png)
[英]Why does service injection in app component cause undefined for URL parameters?
[英]Injection token undefined in service, but found in component
我正在將外部js
庫作為InjectionTokens
添加到Angular 7應用程序中,以便在@Components
和服務中使用它們。 我已經創建了接口, InjectionToken<>
和Provider
,並將Provider
添加到了@NgModule
的providers: []
屬性中。
我一直在關注這個指南就如何注入第三方庫。
當我將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
:
import { Injectable, Inject } from '@angular/core';
import { IHotParser} from './parser/parser.injector';
@Injectable()
export class EntryService {
constructor(
@Inject(HotParser) private parser: IHotParser // HotParser is not defined
) { }
在組件和服務中注入令牌之間有區別嗎? 我試圖將模塊提供者數組的順序更改為無效...
沒關系。 Visual Studio Code的更新沒有警告我沒有在服務的import
語句中導入HotParser
...我看到了以下編譯器錯誤:
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';
錯誤消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.