[英]Provide a service in Angular5 = “is not a function”
我想覆蓋其他模塊中的服務,但出現錯誤“不是函數”
在我的組件(模塊1)中,我注入了服務
public constructor(private chartProgressService: ChartProgressService) {
}
在模塊2中,我覆蓋提供程序中的服務
providers: [
{
provide: Configuration,
useClass: AppConfiguration,
},
{
provide: ChartProgressService,
useValue: MyChartProgressService
},
{
provide: LOCALE_ID,
useValue: 'de-DE',
}
],
這是MyChartProgressService
import {Injectable} from '@angular/core';
@Injectable()
export class InnogyChartProgressService {
public getUnit(): string {
return '';
}
public getValue(currentValue: number, maxValue: number): number {
return currentValue;
}
}
在我的組件中調用this.chartProgressService.getValue()返回錯誤
HeaderComponent.html:11 ERROR TypeError: this.chartProgressService.getUnit is not a function
at ChartProgressComponent.ngOnInit (chart-progress.component.ts:33)
at checkAndUpdateDirectiveInline (core.js:12369)
at checkAndUpdateNodeInline (core.js:13893)
at checkAndUpdateNode (core.js:13836)
at debugCheckAndUpdateNode (core.js:14729)
at debugCheckDirectivesFn (core.js:14670)
at Object.eval [as updateDirectives] (HeaderComponent.html:11)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655)
at checkAndUpdateView (core.js:13802)
at callViewAction (core.js:14153)
我想我需要你的幫助! 謝謝!
還有一件事是,如果您想使用InnogyChartProgressService
import {Injectable} from '@angular/core';
@Injectable()
export class InnogyChartProgressService {
}
那應該像
{
provide: ChartProgressService,
useClass: InnogyChartProgressService
},
在這種情況下,您要引用另一個名為MyChartProgressService
類並更改useClass
根據角度指南,如果您要用新服務替換服務,而不是需要擴展服務,例如角度指南
為此,請用新的Logger替換舊的Logger
[{ provide: Logger, useClass: BetterLogger }]
它將舊的擴展為新的,如下所示
@Injectable()
export class EvenBetterLogger extends Logger {
}
閱讀: https : //angular.io/guide/dependency-injection#alternative-class-providers
問題實際上是以下原因:如果在提供程序定義中使用useValue
,則必須在那里使用實際實例,例如new MyChartProgressService()
或對象文字。 但是,如果您只想給出一個“藍圖”並由Angular自動實例化,請使用useClass
和一個類型,因此在您的情況下,請使用useClass: MyChartProgressService
。
在這個問題中可以找到更多的解釋。
{提供:ChartProgressService, useClass :MyChartProgressService}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.