1

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?

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.