在 Angular5 中提供服务 = "is not a function"

Provide a service in Angular5 = "is not a function"

我想覆盖其他模块的服务,但出现错误 "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() returns 错误

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)

我想我需要你的帮助!谢谢!

{ 提供:ChartProgressService, useClass: MyChartProgressService }

问题实际上如下:如果您在提供程序定义中使用 useValue,则必须在那里使用实际实例,例如 new MyChartProgressService() 或对象文字。但是如果你只想给出一个 "blueprint" 并让它由 Angular 自动实例化,请使用 useClass 和一个类型,所以在你的情况下 useClass: MyChartProgressService.

可以在 question 中找到更多解释。

还有一件事是如果你想使用 InnogyChartProgressService

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

@Injectable()
export class InnogyChartProgressService {
}

那么应该是

 {
    provide: ChartProgressService,
    useClass: InnogyChartProgressService 
},

在你的情况下,你指的是不同的 class 称为 MyChartProgressService 并更改 useClass


根据 angular 指南,如果您想用新服务替换服务而不需要扩展服务,例如 angular 指南

中给出的

为此,用新的替换旧的记录器

[{ provide: Logger, useClass: BetterLogger }]

它在新的中扩展了旧的,如下所示

@Injectable()
export class EvenBetterLogger extends Logger {
}

阅读:https://angular.io/guide/dependency-injection#alternative-class-providers