Exploring Angular: Understanding Events and Addressing the Error Message "subscribe is not a function"

Recently, I delved into the basics of Angular 4 and encountered a roadblock while trying to listen to an emitted event. Let me share a simple example that demonstrates the issue:

DateSenderComponent is sending out the current date to be handled by its parent component AppComponent (as shown below):

import { Component, Output } from '@angular/core';
import { EventEmitter } from "events";

@Component({
  selector: 'app-date-sender',
  template: '<button (click)="sendDate()">Send</button>'
})

export class DateSenderComponent {
  @Output() dateSent = new EventEmitter();

  sendDate(){
    var dt = new Date();
    console.log(dt);
    this.dateSent.emit(dt.toString());
  }
}

The role of AppComponent is to capture the broadcasted date event:

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

@Component({
  selector: 'app-root',
  template: '<app-date-sender (dateSent)="dateReceived($event)"></app-date-sender>'
})

export class AppComponent {
  dateReceived(value){
    console.log('Result: ', value);
  }
}

Following various beginner tutorials, I understood this method for event listening. However, upon loading the page, instead of displaying the received date value, I encounter the following error:

AppComponent.html:1 ERROR TypeError: instance[output.propName].subscribe is not a function

at createDirectiveInstance (core.es5.js:10727)

at createViewNodes (core.es5.js:12086)

at callViewAction (core.es5.js:12530)

at execComponentViewsAction (core.es5.js:12439)

at createViewNodes (core.es5.js:12113)

at createRootView (core.es5.js:11991)

at callWithDebugContext (core.es5.js:13206)

at Object.debugCreateRootView [as createRootView] (core.es5.js:12666)

at ComponentFactory_.create (core.es5.js:9912)

at ComponentFactoryBoundToModule.create (core.es5.js:3448)

Unfortunately, I could not find any clarifying information about this error or resolve it on my own.

One observation worth noting is that when I modify the template of AppComponent to listen to an event that is not being emitted anywhere (for instance

<app-date-sender (someStringSent)="dateReceived($event)"></app-date-sender>
), the error disappears. This suggests a connection between the emitted output event and the template's listener, causing the problem.

Can someone provide guidance on how to address this issue?

Answer №1

EventEmitter must be imported from '@angular/core'

I noticed that in your code you are importing it from 'events'.

Are you positive that you are using the correct module?

Answer №2

The issue lies within this section:

import { EventEmitter } from "events";

To resolve this problem, you need to import EventEmitter from @angular/core in the following manner:

import { EventEmitter } from "@angular/core";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reveal the class to the global scope in TypeScript

ClassExample.ts: export class ClassExample{ constructor(){} } index.html: <script src="ClassExample.js"></<script> // compiled to es5 <script> var classExample = new ClassExample(); //ClassExample is not defined < ...

Unable to locate 'reflect-metadata' module within Docker container on Production Server

I encountered an error: module.js:550 throw err; ^ Error: Cannot find module 'reflect-metadata' at Function.Module._resolveFilename (module.js:548:15) at Function.Module._load (module.js:475:25) at Module.require ( ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

The HTTP GET request was successful, however, there is no data being displayed on the screen

I am currently facing an issue with fetching data from a web server. The data is retrieved successfully as I can see the object in the console log, but it does not render in the component template. export class CountrydetailsComponent implements OnInit { ...

Sorting and categorizing RxJS Observables

Learning about reactive programming is a new and sometimes challenging experience for me. If we have a list of events from a service called event[] The structure of an event is as follows: Event: { beginDate: Date, name: string, type: State } State: ...

Angular2 and the exciting world of Mapbox-gl

I am currently facing an issue with integrating mapbox-gl into my Angular2 application. Despite creating the service, the app is not functioning properly. Service import {Injectable} from '@angular/core'; import * as mapboxgl from 'map ...

What is the best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Initialization error: ServiceIdentifier Symbol(LicencesService) not found in bindings

Encountering an error while compiling the code: Unable to find matching bindings for serviceIdentifier: Symbol(LicencesService) The issue seems to be in the constructor of the HTTP on server.ts file. How can I properly inject the LicencesService? Here is ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents. documents: BehaviorSubject<Document[]> Let me provide you with some insight into the various classes I' ...

Unable to locate partial name

Recently installed the ngx-bootstrap 1.9.2 npm package and encountered an error while trying to compile my Angular project: ERROR in C:/xxx/xx/node_modules/ngx-bootstrap/datepicker/bs-datepicker.component.d.ts (46,15): Cannot find name 'Partial'. ...

Customize the date format of the Datepicker in Angular by implementing a personalized pipe

I am dealing with a datepicker that defaults to the MM/dd/yyyy format, and I need it to adjust based on the user's browser language. For example, if the browser language is English India, then the format should be set to dd/MM/yyyy as shown below. Be ...

Ways to initiate an HTTP request within switchMap upon emission of a BehaviorSubject value

As I delve into writing angular applications in a declarative style, I find myself pondering on the most effective approach for handling POST requests. Specifically, I am facing a dilemma with regards to calling these requests when dealing with a login for ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Adjusting the IntelliSense Functionality in Monaco Editor

Currently, I am testing out the CompletionItemProvider feature for my project. I have implemented two separate CompletionItemProviders. One is set to trigger when any alphabet letter is typed and the other triggers when the user enters a single quote chara ...

Custom font for Ionic styling

Greetings! I come to you with a query regarding font usage. Note: I am developing an app for mobile devices (iOS, Android) using Ionic with Angular. I am looking to incorporate the Poppins font into my application. It works perfectly when accessed on a P ...

tsc is not recognizing the configurations in my tsconfig.json file

Running tsc in my project's directory is causing an error to be outputted (as shown below). This is my first attempt at using TypeScript and Node.js. Please consider me as a complete beginner. Operating system: Ubuntu 15.10 64bits NPM version: 2.4. ...

Transforming encoded information into a text format and then reversing the process

I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer. Here is the line causing the problem: const str ...

Tips for effectively unit testing NgRx selector observables

I'm struggling to replace an NgRx Selector and ensure that the new value is output from the observable. It seems like the call to overrideSelector() isn't functioning as expected. The outcome of this replacement doesn't show up in the final ...