Angular2 Event Emitter holding the most recent value

Is there a method to retrieve the last value from an EventEmmiter immediately after subscribing to it?

The scenario in question involves a list component that utilizes two additional components: a filter and a grid. The filter emits a filter event, while the grid emits a sorting event.

In the list component, I aim to implement the following code:

        Observable
            .combineLatest(filtering$, sorting$)
            .switchMap(([filter, sorting]) => {
                return this.api.list(filter, sorting);
            })
            ...

This is concise and elegant code but encounters two issues:

  1. EventEmitter is not treated as an observable, though easily remedied by wrapping it with an observable.
  2. The API call won't execute until every observable triggers at least once, posing a significant problem.

To address this, I currently utilize a BehaviorSubject from RxJs:

Represents a value that changes over time. Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.

In the filter component, I have implemented:

class UsersListFilter {
    private filteringSource = new BehaviorSubject<UserFilter>(new UserFilter());
    filtering$ = this.filteringSource.asObservable();

    ...
}

And within the list component:

class UsersList {
    @ViewChild(UsersListFilter) private filter: UsersListFilter;
    ...

    setupDataReloading() {
        Observable
            .combineLatest(this.filter.filtering$, this.grid.sorting$)
            ...
    }
}

As depicted, I avoid using EventEmitter altogether. Nonetheless, this solution doesn't align seamlessly with Angular2's conventional approach to child component interaction (@Output).

Your insights are welcome.

Answer №1

Try using this specialized class instead

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

import { ObjectUnsubscribedError } from 'rxjs';


export class CustomEventEmitter<T> extends EventEmitter<T> {

    private _value: T;

    constructor() {
        super();
    }

    get value(): T {
        return this.retrieveValue();
    }

    retrieveValue(): T {
        if (this.hasError) {
            throw this.thrownError;
        } else if (this.closed) {
            throw new ObjectUnsubscribedError();
        } else {
            return this._value;
        }
    }

    emit(value?: T) {
        super.emit(this._value = value);
    }
}

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 in Typescript: TS7006 - The parameter 'xxx' is assumed to have a type of 'any' without explicit declaration

When testing my UserRouter, I am utilizing a json file data.json [ { "id": 1, "name": "Luke Cage", "aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"], "occupation": "bartender", "gender": "male", "height" ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

Storing a reference globally in React and Typescript: Best practices

In my application, I have multiple instances of a specific component called <Item>. Each <Item> needs to display a dynamic tooltip when hovered over. To achieve this, I am utilizing semantic-ui-react and its Popup component. The conventional m ...

Dealing with data returned by GraphQL API using axios

My current method for making the desired post request looks like this: async function fetchMediaList(): Promise<MediaListCollection> { let result = {} as MediaListCollection; await axios .post<MediaListCollection>( "https:// ...

Is there a way to ensure that only individual objects are selected in FabricJS on the Canvas, rather than a group of objects?

One issue I am facing is with my method for selecting objects on the canvas by clicking a button. How do I ensure that it skips selecting groups and only selects individual objects? Generating a group of shapes here: const group = new fabric.Group([ ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

Angular 5: Ensure Constructor Execution Occurs Prior to Injection

I am working with a file that contains global variables: @Injectable() export class Globals { public baseURL:string; public loginURL:string; public proxyURL:string; public servicesURL:string; constructor(platformLocation: PlatformLocation) { ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

In what way can you retrieve scope values (when testing) from an Angular controller implemented in TypeScript?

When working with Angular controllers in TypeScript, you have the option to define your controller in a way that accepts the $scope as an input parameter: class TestCtrl { constructor($scope:ng.IScopeService) { $scope.myData = "Information"; ...

Incorporate an interface for handling potential null values using Typescript

Currently, I am utilizing Express, Typescript, and the MongoDB Node.js driver to develop my API. However, I am encountering an issue with the findOne method as it returns a promise that resolves with either an object containing the first document matching ...

Exploring the wonders of nested object destructuring in ES6

How have you been? I want to remove the property "isCorrect" from a nested object. Original List id: 1, questionText: 'This is a test question for tests', answerOptions: [ { answerText: 'A', isCorrect: ...

Exploring the seamless integration of Next.js, TypeScript, and useContext across

Revision: I realized that I had forgotten to include the following line of code in my Header.tsx component: import Link from 'next/link'; After rectifying this oversight, everything started functioning properly. I am currently struggling with ...

Any idea why the HTML Select dropdown isn't functioning properly in Angular 2?

I am facing an issue with an Angular 2 Form. I am trying to include an html select but it is not working. I have checked the Angular 2 Documentation and even the live examples provided, like the HERO FORM, are not working. You can view the Hero Form Live E ...

Symfony seems to be dropping my session unexpectedly during certain requests

Currently dealing with angular 2, I am encountering issues with requesting symfony where certain requests cause the sessions to be lost. Strangely enough, some requests work perfectly fine while others do not. If anyone has any insight or advice on what co ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

`Implementing a Reusable RadioButton Component in Angular2`

When trying to reuse my component on the same page, I encountered an issue with defining the value of Radio Buttons based on the specific component I'm working with. I have three shared-components that need to be distinguished. If I modify one compon ...

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

Having trouble locating the Nativescript-theme-core file for your Nativescript application?

I'm currently working on a basic barcode scanner app and encountering an unusual error once the app is deployed to a Genymotion emulator. It appears to be searching for the core theme in the incorrect location. Any thoughts on why this issue is occurr ...