Managing input and output using a collaborative service

I've been working on refactoring some code that contains a significant amount of duplicate methods between two components. Component A is a child of component B, and they can be separate instances as intended. The issue I'm facing revolves around emitting data within certain methods, and then struggling to pass those inputs to the template for reasons unknown.

Here's an overview of my current setup:

Both component A and component B are emitting events, and I haven't altered these methods yet because it's difficult to separate that logic. How can I make adjustments to the inputs on the service side and reflect those changes in the component? Any insights or guidance on this?

component A 

export class CompA {
 template: ...
 ...
 inputs [
  'value1'
  'value2'
 ]
 outputs: [
 'doSomething'
 'doSomething2'
 'doSomething3'
 ] 

 public value1: string;
 public value2: string

 addLine() {
 //simple example
  if(this.value1 == ""){
   this.doSomething1.emit(3)

  // the functions are obviously bigger but i need this emit inside the service and catch the event in the component
  }
}

Answer №1

I'm not entirely sure I grasp the question. Perhaps creating a plunker to showcase the problem would shed some light on it.

Generally, if you need to modify data in a service, simply update the values.

For instance:

Service

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

@Injectable()
export class ShareService {
   public info: string;

   setData(newInfo : string){
       this.info = newInfo;
   }

   clearData(){
       this.info = '';
   }
}

Component setting the value

export class PageA {
    constructor(private shareService: ShareService, private router: Router){
    }
    goToNextPage(){
        this.shareService.setData("Example information");
        this.router.navigate(['pageb']);  
    }

}

Component retrieving the value

export class PageB {
    constructor(private shareService: ShareService){ }

    get storedInfo() : string {
      return this.shareService.info;
    }
}

The main idea is to utilize a getter property in the component that retrieves the value (PageB in this case) so it automatically updates whenever the data service value changes.

Does this align with what you were asking about?

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 are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

Display or Conceal Multiple Divisions Using Angular 2

I am looking to implement a functionality using Li lists to toggle the visibility of multiple divs in Angular 2. Initially, all divs on the page will be visible. When viewing on a smaller screen, I want to hide some divs and show a specific div when a cor ...

The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase. Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts. // ap ...

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

The positioning of the button was off-kilter in Firefox

app.component.html: <div class="input-group col-12 d-flex align-items-baseline pb-3"> <p class="mb-0 pb-3 col-12">Verify....</p> <input type="url" class="form-control" id="validationC ...

Communication among sub applications is crucial for the success of Micro Frontends

After researching the best practices for frontend applications, I made the decision to refactor our monolith application. Instead of choosing between micro frontends and mono repo approaches, I decided to merge them both in a unique way. I plan to create ...

Save the application's state of the user in a mean stack program

In my Angular 9 application, I have forms with multiple sections. The first section includes name and personal details, the second part covers primary school information, and the third part focuses on past jobs held by the user. Each part is displayed in a ...

React TypeScript - Issue with passing props to Hooks causing type errors

I have set up a codesandbox project to demonstrate my problem 1) Initially, I created the <Input> component for styling and tracking input content. 2) While everything was functional, adding more forms prompted me to create a useInput hook for easi ...

How to resolve useState problem in useEffect when state is not null

Encountering issues with maintaining state in TypeScript React. A Child component passes a 'terminal' object to the Parent via a function called returnTerminal(). This 'terminal' object is then stored as a useState variable named _obje ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

Extract the initial sentence or the opening 50 words from a data object in Typescript/JavaScript

Is there a way to extract only the initial line or first 50 words from the data retrieved by the API and store it in a variable? In the HTML File: <td *ngIf="customizedColumns?.details_of_non_conformity?.value"> <span [ngCl ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

Debate surrounding the use of .next() in conjunction with takeUntil

Recently, I've observed a change in behavior after updating my rxjs version. It seems that the .next() method this.ngUnsubscribe$.next(); is no longer functioning as it used to: export class TakeUntilComponent implements OnDestroy { // Our magical o ...

Recording changes in SVG size in Angular 2

I am aiming to create an SVG canvas within an Angular 2 template that automatically scales with its parent element and triggers a redraw method when its size changes. While using the onresize property, I successfully receive events but encounter difficult ...

The loading time for the Docker index HTML file page is unacceptably slow

Sample Dockerfile: FROM ubuntu:22.04 RUN apt-get update RUN apt-get install -y nginx COPY -r dist/ /var/www/html/ CMD service nginx start && tail -F /var/log/nginx/error.log After that, run the following commands: docker build -t website . docker ...

Display of environment variables in the production build

In a nutshell, I somehow "downloaded" my app (Ctrl+S or right click+save as) and discovered that my environment variables are not hidden but stored in a file named main.xxxx.js (where xxx is the build hash). I came across a secret key for a service in tha ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

Steer clear of using enum values in typescript to prevent potential issues

I am looking to iterate through an enum type in order to populate options within a react component. Below, you will find the specific enum and a function that retrieves its keys and values. export enum TaskType { daily, weekly, monthly, yearly } ...

Guide to exporting a ReactJS + Typescript component to be used in Vanilla JavaScript and HTML

I have a ReactJS component along with its sub-components styled with CSS. I'm looking for a way to export my component for VanillaJS and HTML without having to import React@17 or 18. If there is an easier method or any alternative suggestions instead ...

Just starting out with Angular and struggling to understand how to fix the TS(2322) error

Main Code: export class TodosComponent implements OnInit{ todos!: Todo[]; localItem: string; constructor(){ const data = localStorage.getItem("todos"); this.localItem = data; if(this.localItem == null){ this.todos = []; } ...