user10274910
user10274910

Reputation:

Cannot invoke an expression whose type lacks a call signature. Type 'EventEmitter<Number>' has no compatible call signatures

I am trying to write a service in which some events are triggered via respective methods in it so that any component in my application can listen to it.

So, I created a custom event in a service as follows

export class EventsService {

@Output() expandNav: EventEmitter<Number> = new EventEmitter();

trigExpandNav() {
this.expandNav.emit(1);
}

constructor() { }
}

Then I included this service as a provider in my component in which I wanted to emit this event via the trigExpandNav method as follows :

import {
Component,
OnInit,
Output,
EventEmitter
} from '@angular/core';
import {
EventsService
} from '../../services/events.service';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
providers: [EventsService]
})
export class HeaderComponent implements OnInit {

eventsService: EventsService;

fun() {
this.eventsService.trigExpandNav();
}

 constructor() {}

 ngOnInit() {}

 }

But I am getting this error

 ERROR in src/app/layout/header/header.component.ts(21,7): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'EventEmitter<Number>' has no compatible call signatures.

I don't know where I am doing it wrong, so please help and Thanks in advance.

IMPORTANT

What I am trying to achieve is :

Suppose I have 2 components. I want to trigger an event from 1st component when a button or link is clicked and listen that event in 2nd component from the html file like this sda

For that I made a service in which I am emitting the event through a method. The thing is it's working as expected.

Upvotes: 2

Views: 3431

Answers (1)

JoshSommer
JoshSommer

Reputation: 2618

You shouldn't be using event emitters for Service's this is a better place for a RxJS BehaviorSubject or Subject. depending on your need.

@Ouput()s and EventEmitters are for Components only

So your service should become something along the lines of:

export class EventsService {

   private expandNavSubject = new BehaviorSubject<number>(null);

   trigExpandNav() {
      this.expandNavSubject.next(1);
   }

   get expandNav$(){
     this.expandNavSubject.asObservable();
   }

   constructor() { }
   }
}

then in your header component inject the service via the constructor with:

constructor(private eventsService: EventsService){}

and call the trigger expand nav function with this.eventsService.trigExpandNav(); in your fun() function

Upvotes: 3

Related Questions