Generate an observable by utilizing a component method which is triggered as an event handler

My current component setup looks like this:

@Component({
    template: `
    ...
    <child-component (childEvent)="onChildEvent()"></child-component>
`
})
export class ParentComponent {
    onChildEvent() {
        ...
    }
}

I am aiming to transform the calls to the onChildFinished method into an observable sequence.

If the method in question was related to a typical DOM event like click or blur, I could have used Observable.fromEvent. However, since there is no native event involved in this case, that approach isn't applicable.

The only solution that comes to mind involves the following implementation:

@Component({
    template: `
    ...
    <child-component (childEvent)="onChildEvent()"></child-component>
`
})
export class ParentComponent implements OnInit, OnDestroy {
    private childEventStream: Observable<void>;

    // The type of this
    // appears to be an internal RxJS object
    private observer: any; 

    onChildEvent() {
        this.observer.next();
    }

    ngOnInit() {
        this.childFinishedStream = Observable.create(
            observer => this.observer = observer;
        );
    }

    ngOnDestroy() {
        this.observer.completed();
    }
}

This process seems inefficient and complex, especially when dealing with multiple handlers. There must be a more streamlined approach available.

Answer №1

Are you in need of an EventEmitter?

To create one, follow this example:

@Component({
    template: `
      <child-component (finished)="onChildFinished($event)"></child-component>
    `
})
export class ParentComponent {

    onChildFinished(data: number) {
        //...
    }
}

The child component utilizes the Output.

@Component({
    selector: 'child-component',
    template : `hello`
})
export class ChildComponent {

    @Output()
    public finished: EventEmitter<number> = new EventEmitter<number>();

    private _imFinishing(): void {
        finished.emit(1);
    }
}

It's possible that I might have misinterpreted your inquiry, but this solution might be what you are looking for.

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

What is the best way to enhance the object type within a function parameter using TypeScript?

If I have a specified type like this: type Template = { a: string; b: string; c: string } I want to utilize it within a function, but with an additional parameter. How can I achieve this efficiently? When attempting to extend the type, TypeSc ...

Implementing basic authentication and Cross-Origin Resource Sharing (CORS) in

I am currently attempting to make a simple HTTP API call using Angular to a standard API with Basic HTTP Authentication. However, I am encountering an issue where the browser is blocking the request with a "Cross-Origin Request Blocked" error message, citi ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

Tips for utilizing Optical Character Recognition in Node.js with a buffer image:

Are you facing difficulties in creating an API that extracts data from an image without saving it on the server? Look no further, as I have a solution for you. When testing with the URL '', everything works perfectly. However, using a buffer or l ...

Typescript error encountered when executing multiple API calls in a loop causing Internal Server Error

I'm relatively new to Typescript/Javascript and I am working on a function called setBias(). In this function, I want to set all indices of this.articles[i].result equal to the biased rating returned by the function getBiasedRating(this.articles[i].ur ...

Creating an Angular service that checks if data is available in local storage before calling an API method can be achieved by implementing a

I am currently working on developing an Angular service that can seamlessly switch between making actual API calls and utilizing local storage within a single method invocation. component.ts this.userService.getAllUsers().subscribe(data => { conso ...

What is the best way to ensure string comparison safety in Angular templates when dealing with null or undefined values?

Okay, so I encountered the following scenario: <span *ngIf="!someItem?.description==''"> The situation is: If someItem is defined and the description is not an empty string. Essentially, this can be interpreted as not equal to any value X ...

How to implement separate environment.ts files for different languages in Angular 12? For example, environment.en.ts and environment.de.ts files

Recently, I've been developing a multi-language Angular application and successfully deployed it to Firebase hosting. If you visit , you'll see the German version. On the other hand, displays the English version of the app. One challenge I enc ...

I am currently leveraging Angular 17, but I have yet to enable Vite. Can anyone guide me on

Despite having the most recent version of NX and Angular, my app has not yet integrated Vite. I've come across online suggestions on how to enable it, but none of them make sense to me because my project doesn't have an angular.json file. Instead ...

What is the reasoning behind the Angular CLI's version displaying as 1 after the installation of version 7

I'm trying to update my global version of Angular CLI to the newest release. Why does ng v still display version 1.3.2 after the update? Just a heads up, I'm using nvm. Snapshot before updating... $ng -v _ _ ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

Issues with CSS Styling not being applied properly on mobile devices in a React App deployed on Heroku

The Dilemma My React app is deployed on Heroku using create-react-app for bundling. The backend is a Node.js written in Typescript with node version 10.15.3. Locally, when I run the site using npm start, everything works perfectly. However, when I view t ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

Mastering the art of Typescript typing

I am attempting to start the REST server for an Aries agent as outlined here: import { startServer } from '@aries-framework/rest' import { Agent } from '@aries-framework/core' import { agentDependencies } from '@aries-framework/nod ...

Encountered an error - 'SyntaxError: unexpected token: ':'' while attempting to load a JSON file for ngx-translate using the Karma test runner

I am currently in the process of setting up system tests for my Angular application. The app utilizes the TranslateModule (ngx-translate) in this manner: TranslateModule.forRoot({ defaultLanguage: 'de', loader: { provide: Tra ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Troubleshooting routing errors when deploying Angular 6 on hosting name.com

After loading my Angular 6 application using CLI in a standard hosting service at name.com, I encountered some issues. Here are the steps I followed: Ran 'ng build --prod' command This command generated the dist folder In the root directory of ...

receiving list items in JSON format rather than XML or Atom

Upon typing the link of a list in my browser, I am able to view all the data in xml/atom format. The screenshot can be found below: https://i.sstatic.net/9jUKV.png In my search for converting this incoming response to JSON, I utilized the "RequestOptionsA ...