What is preventing me from subscribing once more to the same EventEmitter after I have unsubscribed?

I have implemented a subscription in the ngOnInit() method of an Angular2 component and then unsubscribed in ngOnDestroy(). However, after reinitializing the component, I encounter the following error:

ObjectUnsubscribedError: object unsubscribed

The code snippet in my class is as follows:

ngOnInit() {
   this.chatService.getConversationsEvent()
   .subscribe((data:Data<Array<Conversation>>) => {  
      console.log('from correspondence');
   });
   this.scrollToBottom();
}

ngOnDestroy() {
    this.chatService.getConversationsEvent().unsubscribe();  
}

Answer №1

Give this code a try!

observable:any;    
ngOnInit() {
       this.observable = this.service.getEventData()
       .subscribe((data:Data<Array<Event>>) => {  
          console.log('event data');
       });
       this.scrollToBottom();
    }

    ngOnDestroy() {
        if(!observable.closed()){
         this.observable.unsubscribe();  
        }
    }

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

Error: Unable to locate metadata for the entity "BusinessApplication"

I have been utilizing TypeORM smoothly for some time, but out of the blue, I encountered this error during an API call: EntityMetadataNotFound: No metadata for "BusinessApplication" was found. at new EntityMetadataNotFoundError (C:\Users\Rob ...

Using PHP encryption and decrypting with AES in Angular using Crypto-JS

I have successfully implemented encryption and decryption in PHP using aes-256-cbc. However, I am now facing a challenge in decrypting the same content in Angular 7. Encryption in php using aes-256-cbc by following method $this->data ="plaintext&qu ...

"Utilize ngclass to set CSS classes based on enum string values

Is there a way to directly call an element in Angular when using an enum to organize component styles? Instead of writing multiple ng class expressions or dynamically passing them to the element call. button-types.ts export enum ButtonTypes { Primary ...

What steps can I take to resolve a dependency update causing issues in my code?

My program stopped working after updating one of the dependencies and kept throwing the same error. Usually, when I run 'ng serve' in my project everything works fine, but after updating Chartist, I encountered this error: An unhandled exception ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Is there a way to deactivate a button in Angular when an <input> field is blank, without relying on form validation?

Looking for a way to utilize @output in Angular, I have set up an input field with a button. The goal is to send the input field data to the parent component using @output(). My challenge is to disable the button if the input field is empty, without relyin ...

Tips for resolving errors in Angular controls

Setting custom errors in Angular is straightforward with this code snippet: this.form.controls['field'].setErrors({same:true}); However, the process for removing custom errors is not as obvious. Does anyone know how to accomplish this? Are ther ...

The theming feature in Angular 5 with Bootstrap 4 and Bootswatch seems to be malfunctioning

Having trouble implementing bootswatch themes with angular 5 and bootstrap 4? I've added the following to styles.scss: @import "~bootswatch/dist/cerulean/variables"; @import "~bootstrap/scss/bootstrap"; @import "~bootswatch/dist/cerulean/ ...

Tips for maintaining data reactivity while transmitting it to a function

Consider the following setup for my component: <script setup lang="ts"> interface FileMetadata { owner: string, location: string, size: number, // And around 50 mores... } interface File { fileName: string, metadata: FileMetada ...

update or add new data to dataSource to refresh

I am currently working on a project using angular Material and I need to make some modifications to it. Since I am fairly new to Angular, I require assistance in resolving an issue. There is a component in my project that has multiple templates and gener ...

Utilizing ngrx/store in Angular 2 for Search Functionality

In the process of enhancing an angular 4 application, I am working on integrating a search functionality for a data-filled table. The application also utilizes ngrx store to manage state. I am looking for advice on the most effective approach to implemen ...

Retrieving the universal variable in Angular known as `LC_API`

My Angular 6 application has the Live Chat for Angular plugin installed. I'm attempting to utilize the Live Chat Javascript API library to hide the default floating button. When I execute LC_API.hide_chat_window(); in the browser developer console, ...

How to implement a button spinner in Angular 6 without making a service call

I need to toggle the spinner visibility while downloading a PDF file. Here is the code in my Html component: <div > <ng-container *ngFor="let p of selectedStudent.photos.list; let i = index"> <div *ngIf="p.even ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Data service with a variety of return types

I have developed a versatile data service structure that has the following implementation: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable& ...

Preventing nested prototype methods from being transferred between objects in a WebWorker

My challenge is to reserialize an object from a WebWorker while maintaining the same definitions. However, upon receiving the message, all of the prototype functions are lost. The current solution I have only works for first level prototype functions, bu ...

When parameters are added to one route, all other routes cease to function properly

After I added a parameter to one of the routes, all the other routes stopped rendering correctly (i.e., router-view is not working at all). The route /download/:id works as expected. Am I missing something in the setup? I tried leaving and removing the /do ...

An issue has occurred with the NullInjector, specifically regarding the AppModule and Storage in Ionic 4

When attempting to launch my Ionic app using npm start, an error message appears stating "NullInjectorError: No provider for Storage!". I have already included Storage in the app.module.ts file as shown below: imports: \[ BrowserModule, IonicModule ...

Mastering the utilization of bootstrap-select in TypeScript while ensuring "noImplicitAny" is set to true can be quite the challenge, especially when confronted with the issue of bootstrap-select/index

Hello, I am currently exploring Typescript and attempting to incorporate bootstrap-select into a project that requires "noImplicitAny": true. However, I am encountering an issue while trying to import BootstrapSelect from @types/bootstrap-select. The erro ...

Issue encountered while building Angular 4 application for production due to CSS-loader error

Whenever I attempt to build my application using 'ng build', it works fine. However, when I try to run 'ng build --prod --aot=false' to build it for production, I encounter a perplexing error message: devrep@dev-laptop:~/Document ...