Reputation: 568
I want to override a service from an other module, but i got the error "is not a function"
In my component (module 1) i inject the servie
public constructor(private chartProgressService: ChartProgressService) {
}
In module 2 i override the servive in providers
providers: [
{
provide: Configuration,
useClass: AppConfiguration,
},
{
provide: ChartProgressService,
useValue: MyChartProgressService
},
{
provide: LOCALE_ID,
useValue: 'de-DE',
}
],
and this is MyChartProgressService
import {Injectable} from '@angular/core';
@Injectable()
export class InnogyChartProgressService {
public getUnit(): string {
return '';
}
public getValue(currentValue: number, maxValue: number): number {
return currentValue;
}
}
The call this.chartProgressService.getValue() in my component returns the error
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)
I think i need your help! Thanks!
Upvotes: 2
Views: 9161
Reputation: 176896
one more thing is if you want to use InnogyChartProgressService
import {Injectable} from '@angular/core';
@Injectable()
export class InnogyChartProgressService {
}
then it should be like
{
provide: ChartProgressService,
useClass: InnogyChartProgressService
},
in you case you are referring different class called MyChartProgressService
and change useClass
As per angular guide if you want to replace service with new service than you need to extend service , for example given in angular guide
to do this , replace old Logger with new one
[{ provide: Logger, useClass: BetterLogger }]
it extends old one in new one as below
@Injectable()
export class EvenBetterLogger extends Logger {
}
Read : https://angular.io/guide/dependency-injection#alternative-class-providers
Upvotes: 1
Reputation: 17083
The problem actually was the following: If you use useValue
in your providers definitions, you have to use an actual instance there like new MyChartProgressService()
or object literal. But if you want to just give a "blueprint" and let it be instantiated automatically by Angular, use useClass
with a type, so in your case useClass: MyChartProgressService
.
More explanation can be found in this question.
Upvotes: 0
Reputation: 568
{ provide: ChartProgressService, useClass: MyChartProgressService }
Upvotes: 0