Tips for invoking a function from a different component in Angular?

I'm currently working on implementing a method call from one Angular component to another

Inside one.component.ts, there is a task to verify if it's a day off


  export class CalendarComponent implements OnInit { 
     isDayOfWeekDisabled(dayOfWeek: number): boolean {
       let dateIsDisabled = false;
       const workDay= 
       moment(this.viewDate).startOf('isoWeek').add(dayOfWeek, 'd');
       this.disabledAreas.forEach((item) => {
      if (item.start.isSame(moment(workDay)) && 
      item.end.isSame(moment(workDay.endOf('day')))) {
      dateIsDisabled = true;
  }
});
return dateIsDisabled;

} }

On the other hand, in another.component.ts; if the day off value is true, todos for that day should not be displayed:


       filterDateInDisabledArea(): boolean {
         for (const disabledArea of this.disabledAreas) {
             if (isDayOfWeekDisabled()) {
              return false;
             }
           }
            return true;
         }

However, I am facing challenges in establishing a connection between these components.

Answer №1

To determine the appropriate method for calling from one sibling to another, it is recommended to abstract the method into a shared service that both siblings can access:

Service

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  private subject = null;
  data$ = null;

  constructor(private httpClient: HttpClient) {
    this.init();
  }

  init() {
    this.subject = new BehaviorSubject<any>({});
    this.data$ = this.subject.asObservable();
  }

  getProjects(): void {
    const url = 'https://246gg84zg8.execute-api.us-west-2.amazonaws.com/prod/projects/';
    const headers = new HttpHeaders({ 'Content-Type': 'text/plain; charset=utf-8' });
    const options = { headers: headers };
    const value = this.httpClient.get(url, options); // HTTP GET
    this.subject.next(value);
  }
}

Component

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SharedService } from 'src/app/services/Shared.service';

@Component({
  selector: 'app-shared-component',
  templateUrl: './shared.component.html',
  styleUrls: ['./shared.component.scss']
})
export class SharedComponent implements OnInit {
  projects = null;

  constructor(public sharedService: SharedService) {}

  ngOnInit() {
    this.sharedService.getProjects();
    this.sharedService.data$.subscribe(res => {
      if (res.subscribe) {
        res.subscribe(response => {
          this.projects = response.Items.sort(function (a, b) {
            return parseFloat(a.ID) - parseFloat(b.ID);
          });
        }, r => {
          console.log('ERROR', r);
        });
      }
    });
  }
}

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

Testing Angular 4 routing with router.url

Is there a way to simulate router.url in Angular 4 unit testing? In my component, I'm using router.url in the ngOnint function but in my test, the value for router.url is always '/'. ...

Tips for utilizing innerHTML in TypeScript code within an Angular 2 application

Is there a way to utilize innerHTML from TypeScript code in Angular 2 RC4? I'm facing an issue: I need to dynamically add precompiled HTML code when a specific button is clicked. For instance: TypeScript code private addHTML() { // not sure how ...

What are the methods for utilizing conditional types to verify the format of an array containing multiple objects?

Our application is designed to efficiently handle the different structures of an array of objects by utilizing a large conditional type based on specific object properties. The array of objects dictates a sequence of actions to be performed, each action h ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

Unable to manipulate Bootstrap styles in Angular 7 application

Attempting to customize the styling of my breadcrumbs in an Angular App by removing the divider is proving challenging. I've referenced https://getbootstrap.com/docs/4.2/components/breadcrumb/#example, but unfortunately, it's not yielding the des ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

The <servicename> is inaccessible within an error function in Angular2

I encountered an unusual issue in angular2. While the code below is functioning correctly: loginResult.subscribe( (data) => this.response = data, (err) => this._ajaxService.handleError(err, 'A string to summarize th ...

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

Guide on retrieving specific values within an array and mapping them to separate arrays using the HttpClient service in Angular 7+

I'm having a tough time grasping the concept of handling data once it's returned from an Http Request in Angular 7+ The Service responsible for fetching each location is shown below: import { Injectable } from '@angular/core'; import ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Executing Functions in ReactJS When Component is Rendered

I have a question regarding ReactJS: Is there a way to execute a method once all the JSX components (<div> components </div>) have been successfully rendered? If certain components are only rendered under specific conditions, can I trigger a m ...

Numerous issues persist in Angular 6 related to unresolved errors such as crypto, fs, http, https, net, path, stream, tls, and zlib

Each time I attempt to run my Angular 6 app on localhost, a series of errors pop up that include missing modules like 'crypto'. Though some can be installed, others like 'crypto' are built-in. This is baffling as these folders do not ex ...

Guidelines for releasing Node.js microservice client as a stand-alone package within the repository

For my current web application project, I have chosen to implement the client <-> api <-> [microservices] pattern. To challenge myself, I am developing my microservices in Clean Architecture with node.js using Typescript. Although I have alrea ...

Utilize React.useImperativeHandle() for declaring custom types

function App(){ const refEl:React.MutableRefObject<any> = React.useRef(null); // I am uncertain about the appropriate type here. React.useEffect(()=>{ if(refEl.current){ refEl.current.start() } }, []); return <Countdown ref={refEl} ...

Creating a test scenario for a combineLatest Observable using marbles

I am working with an observable that combines two Observable<boolean> using the "or" operation with combineLatest. interface LoadingEventEmitter { isLoading$: Observable<boolean> } export class LoadingService { isLoading$: Observable<bo ...

The IntrinsicAttributes type does not include the property 'path' in the Preact router

I am facing a challenge while developing my website using preact router. Every time I try to add something to the router, I encounter an error stating "Property 'path' does not exist on type 'IntrinsicAttributes'." Despite this error, t ...

Angular component remains hidden post 'ng build' operation

I'm a beginner with Angular and I recently started working on my own single page application project. It was built using the angular cli, and the folder structure is pretty straightforward: - myApp ----e2e ----node_modules ----src --------app ------- ...

Transforming text into numbers from JSON response with *ngFor in Angular 6

I'm currently attempting to convert certain strings from a JSON response into numbers. For instance, I need to change the zipcode value from "92998-3874" to 92998-3874. While doing this, I came across a helpful resource on Stack Overflow. However, I s ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...