What is the best way to pinpoint and eliminate a Subject from an Observable?

Currently, I am utilizing a service to gather user responses from a questionnaire. The sequence of events is outlined below:

  1. questionnaire.component.ts : serves as the main container that receives data from question.service.ts
  2. question-shell.component.ts : Component utilized by questionnaire.component.ts to iterate through questions.
  3. Misc input components : Various components designed for different types of input data, which transmit the user response back up to question-shell.component.ts through an @Output().
  4. question-shell.component.ts : accepts the response and forwards it to answer.service.ts.
  5. answer.service.ts : receives the data and stores it in a variable named _formList.

The structure of the question-shell.component.ts class is detailed below:

export class QuestionShellComponent implements OnDestroy {

    @Input() Data: Question;  //receives data from questionnaire.component

    Response     : UserResponse = {}; //stores user responses



    constructor( private _ans: AnswerService ){}

    ngOnDestroy(){
        this.removeResponse();  //triggers if component toggled off
    }

    grabAnswer(event){          // retrieves user response from Output on
        this.Response = event;  // input component and stores it in Response
        this.sendResponse();
    }

    sendResponse(): void{    // adds response to answer.service
        this._ans.addResponse(this.Response);
    }

    removeResponse(): void{  //removes response from answer.service
        this._ans.deleteResponse(this.Data.id);
    }
}

The content of the answer.service.ts file is provided below:

export class AnswerService {

    private _formList = new Subject<any>();
    public FormList = this._formList.asObservable();

    constructor( private http: Http, private afdb: AngularFireDatabase ){}

    addResponse(event:any){
        this._formList.next(event);
    }

    deleteResponse(event:string){    //the only thing that made sense to try so far

        let target = this._formList.observers.findIndex(a => a.id = event );

        this.FormList.observers.unsubscribe(target);

        console.log(target);
    }
}

All data successfully loads into the answer.service.ts file. The reason why I'm calling the OnDestroy method is because users may switch their answers, potentially closing one set of questions while opening another. Currently, when switching back and forth between answers, more instances of the same questions are being added instead of replacing them. This is why I need to delete previous responses when a component closes.

However, I am encountering an error message stating:

Cannot read property 'unsubscribe' of undefined.

In my initial attempt, I tried targeting just _formList, resulting in an error with the console.log() output indicating:

this._formList.observers.unsubscribe is not a function

I came across the unsubscribe() method while trying to figure out how to properly use splice(), believing that was the solution needed. At this point, I feel lost. Everything else functions correctly, and the responses sent from the component's OnDestroy method are logged in the console, pointing to this issue as the probable cause. If more code snippets would help in understanding the situation better, please let me know, and I'll provide them promptly.

Answer №1

One helpful technique is employing the filter method to remove unwanted information from your Observable stream.

Take a look at this code snippet using the filter function on observers within the _formList object to refine the data being passed through:

Answer №2

Consider implementing it in the following way :

component.ts

import { Subscription } from 'rxjs/Rx';

export class Component {

    private _formList = new Subject<any>();
    private subscription: Subscription;

    removeElement(event:string){
         this.subscription = this._formList.observers.findIndex(a => a.id === event );
         this.subscription.unsubscribe(); 
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        this.eventManager.destroy(this.eventSubscriber);
    }

}

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

Guide to setting up a universal error handling system compatible with forkJoin in Angular 6

I recently implemented error handling in my app following the guidelines from the official Angular 6 tutorial in rest.service.ts ... return this.http.get(url).pipe(catchError(this.handleError)); } private handleError(error: HttpErrorResponse) ...

The FAB button animation is causing delays in the transition process and is not functioning as originally anticipated

I am facing an issue with the FAB button and 3 Icons. The functionality is working fine on click for both show and hide actions, but the transition is too delayed. I want the icons to appear step by step, even though I have adjusted the transition delay se ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Steps for sending angular form data to a .Net backend that requires an autoincrement id:

When trying to insert data into an SQL database through a .Net API endpoint, I encountered an issue with the request body specifying that the ID is auto-incremental. Status 500: Cannot insert explicit value for identity column in table 'StockFeed&ap ...

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

MyApp is encountering issues resolving all parameters

I'm encountering an issue that none of the other similar questions have been able to help me solve. Can anyone offer assistance? I've already attempted removing parameters one by one, but I'm still stuck. Can't resolve all parameters f ...

Is there a program available that can efficiently convert or translate JSON objects into TypeScript types or interfaces?

Can anyone recommend a tool that can easily convert a JSON object into a TypeScript type or interface? An example input would be something like this: I'm hoping to paste the JSON object into the tool and receive an output structure similar to: expor ...

Angular 2 file upload encountering CORS issue leading to 401 unauthorized error

Encountered a "401 Unauthorized" error in Chrome and Firefox while attempting to upload files using angular 2 CLI to an apache2-server with a PHP backend. Despite trying three different node modules, the issue persists from the OPTIONS-preflight stage, ...

How do I properly type when extending Button and encountering an error about a missing component property?

Currently in the process of transitioning from MUI v3 to v4. My challenge lies with some Button components that are wrapped and have additional styling and properties compared to the standard Material UI Button component. Ever since upgrading to v4, I&apos ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Rule in Eslint for Typescript that enforces explicit typing and prohibits the use of implicit "any

Starting a fresh typescript project with eslint, I'm facing an issue in setting up eslint rules for the tsc command to run smoothly without errors. Specifically, I'm encountering difficulty with the "noImplicitAny" rule defined in tsconfig.json, ...

A software piece producing a JSX element that generates a single function

Is it possible to create a JSX element or component that returns a single function as its child? For instance: interface ComponentChildrenProps { someProp: string; } const Component: React.FC<ComponentProps> = ({ children }): JSX.Element => { ...

The CSS property object-fit: cover is unable to properly display JPEG images with EXIF orientation greater than 1

I'm having trouble with my Angular app and creating a gallery of photos from my Samsung Galaxy. I am using the "object-fit: cover" css attribute for a nice design, but it only seems to work correctly when the image has an EXIF "orientation" property e ...

Is there a way to deactivate the click function in ngx-quill editor for angular when it is empty?

In the following ngx-quill editor, users can input text that will be displayed when a click button is pressed. However, there is an issue I am currently facing: I am able to click the button even if no text has been entered, and this behavior continues li ...

Guide on accessing intellisense for mapGetters, mapActions in Vuex using TypeScript without the need for class-style or decorators syntax

I have been using Vue.js and Vuex for a while now, but always with JavaScript. Recently, I decided to try using Vue with TypeScript, specifically with nuxt.js, but without utilizing decorators or style-class-components. I want to stick to the normal Vue s ...

Creating a variety of themes with unique color palettes for Angular Material along with custom-designed components

One of the goals for my app is to have multiple themes, including Angular Material themes, with the ability to define custom colors for specific components and elements that are not part of Angular Material. It's important that when I change a theme, ...

What is the reason this union-based type does not result in an error?

In my TypeScript project, I encountered a situation that could be simplified as follows: Let's take a look at the type Type: type Type = { a: number; } | { a: number; b: number; } | { a: number; b: number; c: number; }; I proceed to defi ...

Convert a string into a component

I need to generate a routing file in my Angular Project where all path and component names are stored in a database. The components will be selected based on the user's login rights. Currently, I am looking to create a route array in the routing mod ...

Typescript Error: Issue encountered while passing props. Unable to access properties as they are undefined

I encountered an issue where I created an object of a certain type and attempted to pass it to a component. However, when passing the props, I received an error message stating that it cannot read properties of undefined ('stepOne'). The error sp ...

The ts-mocha test does not play well with the use of node-fetch library

I have set up ts-mocha and node-fetch to run a unit test, but I am encountering the following error: TypeError: Unknown file extension ".ts" for ... The content of the file is as follows: import fetch from 'node-fetch'; export defau ...