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

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Having trouble with Three JS shadows not displaying correctly?

I recently built an interactive 3D model on my website using ThreeJS, but I'm facing an issue with getting the shadows to work properly. As a beginner in ThreeJS, I might be missing out on some crucial steps. Below is the JavaScript code I've us ...

What is the reason for TypeScript allowing this promise chain without any compilation errors?

Although I am still relatively new to Typescript, I find myself grappling with a particular issue that has been perplexing me. I am unsure why the following code snippet triggers a compilation error: // An example without Promises (does not compile) funct ...

Two-way conditional type mapping

Currently, I am working on mapping the various "data types" of an object to a corresponding "schema" type. If the property's data type is boolean, it should be mapped to the "BooleanComponents" type The code snippet below demonstrates how this can ...

Ways to retrieve Payload following the Request url access

Currently utilizing Selenium with Python to conduct website testing, I successfully accessed the Request link and now aim to access the Payload. Below is an image displaying the process: view image description here driver = webdriver.Chrome(options=option) ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

It seems that an error has occurred: DOMException was thrown because the attempt to run 'importScripts' on 'WorkerGlobalScope' has failed. The script located at 'http://localhost:4200/BlinkCardWasmSDK.js' was unable to load properly

Recently, I attempted to integrate this credit card reader into my Angular application. Despite carefully following all the installation steps and obtaining a valid license key, I encountered the following error: Error during the initialization of the SDK! ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Encountering the 'Default setting for timestampsInSnapshots now set to true' error in Firestore console

Encountering a Firestore error in the console while using Angular. @firebase/firestore: Firestore (5.8.3): The timestampsInSnapshots setting now defaults to true and does not require explicit setting. It is advised to remove it from firestore.settings( ...

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

Using Typescript: Generate keys in function return depending on parameter

Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while de ...

npm encountered an issue: EPERM error - the operation is not permitted and cannot unlink the file

Operating System: Windows 10. NPM Version: 6.9.0 Node Version: 12.4.0 I am currently developing an Expo application. I am attempting to install all the necessary packages for my Expo application using 'npm install'. However, I encountered an err ...

Adal TypeScript Document

Recently, I've been experimenting with the TypeScript version of adal.js. As part of my setup process, I'm referring to this link to install adal.ts. However, after executing the command: npm install adal-typescript --save a new "node_modules" ...

Loading components in an Angular CLI project with the base URL

I recently created an Angular CLI project with various components and transferred it to my school's domain using FileZilla. However, I am looking for a way to automatically redirect the application to the HomeComponent upon loading instead of the AppC ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...

Error: The function _this[("render" + data.type)] is not defined as a valid function

https://i.stack.imgur.com/Y5Dz5.jpg I encountered an error in the console that I can't seem to figure out. Despite following the Syncfusion library's documentation, the error persists. Here is the code snippet that I implemented: import React f ...

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...