Moving information from two modules to the service (Angular 2)

Recently in my Angular2 project, I created two components (users.component and tasks.component) that need to pass data to a service for processing before sending it to the parent component.

Code snippet from users.component.ts:

  Import { Component } from '@angular/core';

  @Component({
    selector: 'users',
    templateUrl: 'app/users.component.html',
    styleUrls: ['app/users.component.css']
  })
  export class UsersComponent {
    // Code implementation for users component...
  }

Code snippet from users.component.html:

<div class="addUser" id="addUser">
                <!-- HTML code for adding user goes here -->
</div>

Code snippet from tasks.component.ts:

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

        @Component({
            selector: 'tasks',
            templateUrl: 'app/tasks.component.html',
            styleUrls: ['app/tasks.component.css']
        })
        export class TasksComponent {
            // Code implementation for tasks component...
        }

Code snippet from tasks.component.html:

<div class="addTask" id="addTask">
                    <!-- HTML code for adding task goes here -->
                </div>

Compare.service.ts:

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

@Injectable()
export class CompareService {
    // Service functionality code will go here...         
}

I am aiming to achieve a structure similar to this: enter image description here

From users.component, I intend to extract designUsers, FrontendUsers, and BackendUsers. Similarly, from tasks, I want to retrieve designTasks and other arrays. My question is about the feasibility of implementing such a structure, or if not possible, any alternate ideas would be greatly appreciated. Thank you!

Answer №1

Take a look at this plunkr demonstration. The example showcases two child components, each capable of altering the state of a specific service.

@Component({
  selector: 'child1',
  template: `
      <button (click)="handle()">child 1</button>
  `,
})
export class Child1Component {
  constructor(private service: Service) {}

  handle() {
    this.service.child1State = true;
  }
}

Additionally, there is a parent component that is monitoring changes in the service's state:

@Component({
  selector: 'my-app',
  template: `
    <div>{{state}}</div>
    <child1></child1>
    <child2></child2>
  `,
})
export class App implements OnInit {
  state = 'unset';

  constructor(private service: Service) {}

  ngOnInit() {
    this.service.observable.subscribe(val => {
      if (val) {
        this.state = 'set';
      } else {
        this.state = 'unset';
      }
    });
  }
}

Lastly, let's explore the service itself. It monitors changes to the states and notifies the subscriber-component accordingly:

@Injectable()
export class Service {
  private _child1State = false;
  private _child2State = false;
  private subject = new Subject<boolean>;
  observable = this.subject.asObservable();

  set child1State(val: boolean) {
    this._child1State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  set child2State(val: boolean) {
    this._child2State = val;
    if (this.isAllSet()) {
      this.subject.next(true);
    }
  }

  private isAllSet(): boolean {
    return this._child1State && this._child2State;
  }
}

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

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

What is the best way to extract the singular PDF link from a webpage?

Currently, I am attempting to utilize Selenium in Java to access DOM elements. However, I have encountered an issue while testing the code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is n ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...

Utilize OpenLayer3 to showcase Markers and Popups on your map

I am currently exploring how to show markers/popups on an osm map using openlayers3. While I have come across some examples on the ol3 webpage, I'm interested in finding more examples for coding markers/popups with javascript or jquery, similar to som ...

Having trouble with jQuery attribute selectors? Specifically, when trying to use dynamic attribute

This is the code I am working with $("a[href=$.jqURL.url()]").hide(); $.jqURL.url() fetches the current page URL. Unfortunately, this code is not functioning as expected. Is there a way to dynamically select elements? ...

What could be the reason for the issue with Backbone.js and modal window breaking on IE9?

I have a basic contact management table in backbone.js that utilizes twitter's bootstrap-modal to display the form input. While everything works smoothly in Firefox and Chrome, I am encountering issues with the modal not appearing in IE 9. Additional ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

Is there a deeper philosophical rationale behind choosing to use (or not use) enums in TypeScript, along with string union types?

Recently, I delved into the world of enum and const enum in Typescript, causing some confusion. I grasped that const enum gets transpiled into simple values while regular enums do not. I also recognized certain distinctions between using string union type ...

Exploring Angular 2: The Power of HTTP Observables for Managing Asynchronous Operations. Exploring the

When working with a form that fetches data using an http observable, I encountered the need to disable the submit button while awaiting the response. Currently, I am setting the status code on each component/form to indicate running before calling the sub ...

What are some ways I can improve the readability of this if-else function in Javascript ES6?

As a newcomer to React development, I am currently in the process of tidying up my code. One issue that I am facing is how to deal with a particular function while minimizing the use of if-else statements. const calculatePerPage = () => { if ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

A step-by-step guide on integrating a Django template tag and HTML element into an HTML page using Javascript

Is there a safe way to insert HTML that includes Django template tags using JavaScript in my project? For instance, if my template contains the following code: <div id="some-element"> <span id="my-tag">{{ my_data }}</sp ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Discovering the precise location of the required() file

When using the require function in the `node` console with commands such as require('path') or require('assert'), how can I determine the absolute path of the file that was loaded? I have searched everywhere for a clear answer without ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Caution: React does not support the `textColor` prop for a DOM element

Receiving an alert message saying: Warning: React does not recognize the 'textColor' prop on a DOM element (all other functionalities are functioning properly). This is how I'm using it in my component: import { ImageWithFallback, Paper, Ta ...

Discover the power of React Meteor, where reactive props and inner state work together

I am working with a component that utilizes the draft-js library for text editing. import React, { Component } from 'react' import { EditorState, convertToRaw } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' imp ...

Enhance the numerical value displayed in jQuery UI tooltips

I have folders with tooltips displaying text like '0 entries' or '5 entries' and so on. I am looking for a way to dynamically update this tooltip number every time an item is added to the folder. The initial count may not always start a ...