Angular - Sharing data between components with response value

I am currently in the process of restructuring my project, focusing on establishing communication between unrelated components while also waiting for a return value from a function call.

Imagine having component1 with function1() and component2 with function2(), both connected through the component.service.

Here is an example of component1:

import { Component, OnInit } from '@angular/core';
import { ComponentService } from '../component.service';

@Component({
  selector: 'component1',
  template: ''
})
export class Component1 implements OnInit {
    
  constructor() {}

  ngOnInit() {
    
  }

  function1() {
    //do something
    
    let parameter: any = "some Parameter";
    let returnValue = function2(parameter);

    //do something else
  }

}

And component2:

import { Component, OnInit } from '@angular/core';
import { ComponentService } from '../component.service';

@Component({
  selector: 'component2',
  template: ''
})
export class Component2 implements OnInit {
    
  constructor() {}

  ngOnInit() {
    
  }

  function2(parameter: string) {
    //do something
    
    return parameter + "did something with it";
  }

}

Lastly, the componentService:

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

@Injectable({
  providedIn: 'root'
})
export class ComponentService{

  constructor() { }

  //???
}

I'm looking for guidance on how to structure the service so that function1() can effectively utilize the returned value from function2(). Any advice on the appropriate setup would be greatly appreciated. Thank you!

Answer №1

It's important to keep in mind that you won't be able to directly call a function from component2 within component1. This is where services come into play - they allow you to store and share data/logic between components by injecting the service into both.

    @Injectable({
      providedIn: 'root'
    })
    export class ComponentService{
    
      constructor() { }
    
      getSomeData() {
        return '' // specify what data is needed here
      }
    }

In each component, remember to:

  @Component({
      selector: 'component2',
      template: ''
    })
    export class Component2 implements OnInit {
    
      constructor(private componentService: ComponentService) {}

      ngOnInit() {
        
      }

      function2(parameter: string) {
        // perform necessary actions
        
        return this.componentService.getSomeData()
      }

    }

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

Navigate to a nested page in React router and automatically open a new page whenever there are parameters passed

I am currently using create-react-app to build my project and I am working on implementing dynamic routing. My site has three main pages: Accordion, Movies, and MovieDetail. The Movies page displays a list of movies fetched from swapi. The goal is to have ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Dealing with Nested Body Payload in PATCH Requests with Constructor in DTOs in NestJS

Within my NestJS environment, I have constructed a DTO object as follows: export class Protocol { public enabled?: boolean; public allowed?: boolean; constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor this.enabled = ...

Angular only allows click events to trigger during a push

Is there a way to reveal the password without requiring a click, but simply by pushing on an eye icon? My code HTML <input [formControlName]="'password'" [type]="isShow ? 'text' : 'password'" class=&qu ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

When utilizing dynamic binding within *ngfor in Angular 4, the image fails to display properly

I'm encountering an issue with an <img> tag that isn't behaving as expected in my code snippet: <div *ngFor="let familyPerson of userDataModel.family" class="col-md-6 col-lg-4 family-member"> <div class="fm-wrapper"> ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

Updating objects in Angular 8 while excluding the current index: a guide

this.DynamicData = { "items": [ { "item": "example", "description": "example" }, { "item": "aa", "description": "bb" }, ...

implementing dynamic visibility with ngIf directive in Angular

header.component.html <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class="navbar-brand">Recipe Book</a> </div> <div class="collapse na ...

What is the proper way to tap into the features provided by DefinitelyTyped in typescript?

While working on my Angular2 app that deals with money amounts, I decided to use dinero.js to handle money values. However, I am encountering difficulties in accessing certain features in Typescript. Following the instructions, I installed the DefinitelyT ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

The installation of Clarity through the command 'ng add @clr/angular' does not succeed

Following the guidance in 'Chapter 3: Building an Issue Tracking System using Reactive Forms' from Angular Projects: Discover Angular 12 with 10 innovative projects and cutting-edge technologies, 2nd Ed. by Aristeidis Bampakos. This chapter&apos ...

Typescript - any of the types imported from a module

Currently, my code looks like this: import * as Types from '../schema/types'; and I'm looking to achieve something along the lines of: let a: Types; This would signify that a should be one of the various types exported from the file types. ...

When attempting to navigate to the index page in Angular, I encounter difficulties when using the back button

I recently encountered an issue with my Angular project. On the main index page, I have buttons that direct me to another page. However, when I try to navigate back to the index page by clicking the browser's back button, I only see a white page inste ...

An error occurred while attempting to generate two requests on the API

My online store consumes an API, but I am having trouble with the requests that the site is making. Every time I make a request, I receive two: one with OPTIONS and another with POST. This causes the API to become jumbled up. Can anyone offer some assist ...

What could be the reason for the malfunctioning of the basic angular routing animation

I implemented a basic routing Angular animation, but I'm encountering issues where it's not functioning as expected. The animation definition is located in app.component.ts with <router-outlet></router-outlet> and two links that shoul ...

Combining two asynchronous requests in AJAX

In the process of customizing the form-edit-account.php template, I have added ajax requests to enhance the functionality of the account settings form. The form allows users to modify their name, surname, age, and other details. While the ajax implementati ...

Exporting stylesheets in React allows developers to separate

I am trying to figure out how to create an external stylesheet using MaterialUI's 'makeStyles' and 'createStyles', similar to what can be done in React Native. I'm not sure where to start with this. export const useStyles = m ...