Ben Ben - 1 month ago 17
TypeScript Question

Typescript : Call instance method

I have an interface:

export interface ISearchService {
search(terms: string): Observable<any>;
}


I have two services implementing this interface:

SearchMaleEmployeeService:

@Injectable()
export class SearchMaleEmployeeService implements ISearchService {

constructor() { }

public search(terms: string): Observable<any> {
console.log('call: SearchMaleEmployeeService.search ' + terms);
}
}


SearchFemaleEmployeeService:

@Injectable()
export class SearchFemaleEmployeeService implements ISearchService {

constructor() { }

public search(terms: string): Observable<any> {
console.log('call: SearchFemaleEmployeeService.search ' + terms);
}
}


In my search.component, I would like to call the search method of the service.

My search.component:

export class SearchComponent {
constructor(@Inject('ISearchService') private searchService: ISearchService) { }

onSearch(terms: string) {
this.searchService.search(terms);
}
}


And finally, in the component which hosts SearchComponent:

providers: [
{ provide: 'ISearchService', useValue: SearchFemaleEmployeeService}
],


When I run the onSearch method in SearchComponent, I got this error:

EXCEPTION: Error in ./SearchComponent class SearchComponent - inline template:0:127 caused by: this.searchService.search is not a function


I think this is because I'm trying to call a method from a interface, but when I
console.log
this.searchService
, it returns
SearchFemaleEmployeeService
, that mean that this is the good instance. Why do I have this error?

Answer

Because you're using useValue

{provide: 'ISearchService', useValue: SearchFemaleEmployeeService}

which just uses the value you provide, which is a class, which in JS is a function. You should instead use useClass, then Angular will create it for you.

{provide: 'ISearchService', useClass: SearchFemaleEmployeeService}
Comments