Execute the function when the observable is subscribed to

I'm currently working on creating a custom component that can interact with an observable passed in through an input. The goal is to show/hide elements based on the state of the observable. Here's what I have in mind:

@Input() observable: Observable<any>;
ngOnInit() {
    this.observable.onSubscribe(() => {
        // display element, perform logic at the start;
    });
    this.observable.onCompleteOrNext(() => {
        // hide element, execute logic at the end;
    });
}

While exploring the rxjs documentation, I came across the possibility of using let like so:

this.observable.let((o: Observable) => {
    // execute logic.
    return o;
});

However, this approach feels like a workaround and I am unsure how to handle actions when the observable completes. I anticipate the observables to be asynchronous, such as HTTP requests, so the component needs to handle them accordingly.

In terms of handling completion, I initially thought about using do function:

this.observable.do(() => {
    // execute logic upon observable completion.
    // unfortunately, not triggering as expected.
});

Unfortunately, unless the `do` function is defined during observable creation, it doesn't get invoked. Although Angular2 allows direct binding of views to observables, I require the capability to perform actions based on the observable, rather than just showing/hiding elements.

My attempts at research haven't yielded satisfactory results, and the rxjs documentation isn't providing clear guidance. I believe this should be a straightforward task, but it seems like my approach might be flawed.

Answer №1

To add functionality to the child component, you can implement hook methods:

export class ChildComponent {
    onActivate(){}
    onUpdate(){}
    onFinish(){}
}

Within the parent component, utilize ViewChild to access the ChildComponent, and then subscribe to the observable to trigger the hook methods at specific points:

  • upon subscribing
  • when data is updated
  • after the process completes

.

export class ParentComponent {
    @ViewChild('child') child:ChildComponent;
    ...
    this.observable.subscribe(
        data => this.child.onUpdate(),
        error => {},
        () => this.child.onFinish()
    );
    this.child.onActivate()
}

Interactive example

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

React and the turn.js library (please note that turn is not a predefined function)

I'm trying to integrate turn.js with React by following an example I found here: https://codesandbox.io/s/005xlk45mn After adapting the code to my project, I encountered the following error: TypeError: jquery__WEBPACK_IMPORTED_MODULE_6___default(... ...

Having trouble getting the three.js EffectComposer to function properly

Seeking guidance on using EffectComposer for postprocessing renders, as my basic setup doesn't seem to be rendering anything on the screen. Any ideas on what I might be missing? <!doctype html> <html> <head> <title>game& ...

Triggering ngSubmit function when button is clicked inside an Ionic alert

My ionic app is up and running, utilizing a template driven form in Angular to gather user input. I'm using ngSubmit to pass this data to my ts.file. My challenge lies in triggering the ngSubmit function through a 'No and save data' button w ...

When I tried to install npm, I encountered an error message stating "npm ERR! ERESOLVE could

I have exhausted all possible solutions - updating node, angular, and restarting my PC, but I am still encountering this error and I cannot figure out why. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @ng-bo ...

Issue with Knockoutjs Custom Binding for Radio Button Groups Failing to Update Selection

I am currently working on creating a unique custom binding in knockout that is similar to the default options binding handler, but instead of a dropdown, it utilizes radio buttons. Whenever an item is added to the array, the update is triggered. However, ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...

How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table. Here is the script I am using: <script> ex ...

Creating an array with user-selected objects in IONIC 3

I've been attempting to separate the selected array provided by the user, but unfortunately, I'm having trouble isolating the individual elements. They are all just jumbled together. My goal is to organize it in a format similar to the image lin ...

Error: The Node Express Server is unable to locate the requested resource at "/

const http = require("http"); const myApp= require('./myApp'); const portNumber = 8080; const myServer = http.createServer(myApp); myServer.listen(portNumber) ...

Tips for transferring the "close" function from a modal template to the HTML of another component in Angular 5

Recently, I started learning angular 4 and I need some assistance with a specific issue. I have a component that contains a modal template. Component :- import {Component} from '@angular/core'; import {NgbModal, ModalDismissReasons} from &apos ...

We encountered an issue while trying to utilize the react-awesome-query-builder npm package within our next.js project, specifically struggling to include multiple

I am attempting to create a query builder similar to the demo using the provided documentation ... when I add more fields in the config, new options appear in the dropdown ... I tried using multiple Builder components to create more fields and even experim ...

Implement a feature on React using hooks that detects when a user clicks

I'm attempting to utilize React hooks to check if a user has clicked outside of an element. I'm using useRef to grab a reference to the element. Could someone help me troubleshoot this? I'm encountering the following errors and referencing ...

Error encountered: expected application router to be connected

I encountered an error while trying to migrate from next 12 to next 13 on my old project. Check out the Console Error Log Despite looking for faults in my code, I couldn't find any reason for these errors. Even after extensive Googling, no solution ...

Managing the scrolling direction horizontally with waypoints.js

As I work on creating a custom wizard form with waypoints, I've encountered an interesting issue that has left me puzzled. In my sample CODEPEN, you can see two pages of the wizard process to better understand the problem. Upon clicking the forward ...

Ability to utilize an alternative attribute type within a TypeScript object

Within my class, I have: class Target { ... readonly overlay: { type: 'none' } | { type: 'centering', style?: { color?: string, offset?: number, size?: number, } } | { type: 'enterin ...

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

What is preventing the visibility of my invoice items when I try to make edits to my invoice?

Currently, I am utilizing Laravel 5.7 and VueJs 2.5.* in my project. The issue I am facing is related to a Bootstrap Model that I use for creating and editing TicketInvoice and its associated TicketInvocieItems. When I try to edit, the Bootstrap Model open ...

React Alert: It is important for every child within a list to have a distinct "key" prop, not due to a missing key in the map

My current project involves developing a React 18 application. While working on one of the pages, I encountered the following error: https://i.sstatic.net/9Mk2r.png I am aware that this type of error is often linked to the absence of a unique key in the m ...

What is the best way to create a large-scale matrix using SVG technology?

I want to create a 10000X10000 matrix in canvas/svg, with each cell containing a square. I attempted to accomplish this using canvas and two loops: for(i=0; i<10000; i++){ for(j=0;j<10000; j++){ /*some drawing code*/ console.log(i,' ...