Using Angular 6 to trigger a function from one component to another, without altering the data

I am completely new to Angular 6 and I'm working with two components: header and dashboard.

Within my header component, I have a notification popup that displays notifications with options to accept or delete them.

On the other hand, in my dashboard component, I show a list of accepted notifications.

My goal is to update the dashboard list whenever a new notification is accepted from the header.

In the header component, here's what I've included:

import { DashboardComponent } from '../../pages/dashboard/dashboard.component';

// Provided the dashboard component

@Component({
  selector: 'app-siteheader',
  providers:[DashboardComponent ],
  templateUrl: './siteheader.component.html',
  styleUrls: ['./siteheader.component.css']
})

// Called the dashcomp in the constructor

 constructor( private dashcomp: DashboardComponent, private dashboardservice: DashboardService, private authenticationService: AuthenticationService) { }

// Notification accept action

actionaccept(id){

    this.authenticationService.acceptaction(id)
            .subscribe(
                data => {  

// Called the dashboard function

                   this.loaddashboard();
                }
            );

  }

// This function triggers the dashboard component's function

 public loaddashboard() {
        console.log('called');
        this.dashcomp.dolist('future'); 
      }

Inside the Dashboard component:

dolist(type) {
    console.log('dasss');
     this.dashservice.listengagement(type,this.page,this.limit)
            .subscribe(
                data => {    
                  console.log(data);
                   this.futureloader = false;
                   this.futurelist = data['result']; 
                   this.futuretotal = data['count'];

                }
            );
  }

The results are displayed in the dashboard HTML using ngfor

However, I'm encountering an issue where triggering the dashboard function from the header shows the console log but doesn't change the output in the dashboard. Am I overlooking something important?

Answer №1

In order to display your list in the HTML, you should obtain an Observable of the list and utilize the async pipe with ngFor. Additionally, the method in which you import the dashboard component within the header component is not recommended. A better approach would be creating a service specifically for managing your list, and then injecting this service into both components.

Answer №2

To utilize the power of rxjs, consider using Subject

Start by creating a new file named common.service.ts

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

@Injectable()
export class CommonService {

  subject$ = new Subject<any>();

}

Next, in your header.component.ts, invoke the next method to update the value,

constructor(private commonService: CommonService) { }

loaddashboard() {
    console.log('called');
    this.commonService.subject$.next('future');
}

Lastly, in the dashboard.component.ts, subscribe to that event

constructor(private commonService: CommonService) { }

ngOnInit() {

    this.commonService.subject$.subscribe(data =>{
      console.log('response from header is => ',data);
    });
}

Check out the working demonstration on Stackblitz

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

I am hoping to refresh my data every three seconds without relying on the react-apollo refetch function

I am currently working with React Apollo. I have a progress bar component and I need to update the user's percent value every 3 seconds without relying on Apollo's refetch method. import {useInterval} from 'beautiful-react-hooks'; cons ...

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

The way to find the prefix for the npm global path

Is there a specific option to pass to npm that will display the path it uses for global modules (-g)? Alternatively, is there another method to determine the global path prefix used by npm? I am aware of the location where global modules are stored on my ...

Utilizing TypeScript/React to Access Data from an Excel Spreadsheet

Hey there! I've been working on a Single-Page-Application with Typescript and React, and now I need to read data from an Excel sheet. The xlsx Library (npm) seems to be the way to go, but I'm having trouble getting it to work. Can anyone offer an ...

The installation of loopback-connector-mongodb through npm failed

As a novice in node.js, I am eager to learn loopback. My attempt to follow a tutorial on loopback ran smoothly until I encountered difficulties while trying to install the loopback connector for MongoDB. npm install --save loopback-connector-mongodb I ca ...

The issue of Angular child components rendering before receiving parent data

My current challenge involves a parent component (app.component) making an http request, storing the result in this.stats and then passing it as a prop to the child component (progression.component). The issue arises when my child component tries to render ...

Toggle the visibility of a modal in code across various components in an Angular 4 project using Typescript

As I was working on my university App, I encountered an issue while attempting to open a Bootstrap modal in code from a different component. Opening a component in code from the same component posed no problems for me as I use JQuery and it functions perfe ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Utilizing React Custom Hooks for Firestore Data Retrieval

I recently developed a React custom hook that interfaces with a Firestore database. I followed the guidelines provided on the Firebase website, but I encountered an issue upon re-rendering the component. After refreshing my app, the useEffect hook function ...

Angular 2 implementes a loading spinner for every HTTP request made

My objective is to implement a spinner functionality whenever an HTTP request occurs in my Angular app. Essentially, I want the user to see a loading screen during these requests within my app component. The setup for my spinner component and spinner servi ...

Passing complex JSON data through Angular's routerLinkIs passing complex JSON

Currently, I am utilizing Angular 5 and have the following ngFor loop: <div class="row margin-v-20"> <my-tile [routerLink]="['/secondPage', item.id, 'item-list']" *ngFor="let item of listaOfItem" [item]="item"></my-t ...

What is the process for installing JPM on a Windows operating system?

While trying to follow the tutorial on installing JPM for Windows found in this link and also this one, I encountered some issues. The tutorial instructed me to install node.exe in the directory C:\nodejs. However, even after following these steps, I ...

Setting up domain configurations for multi-tenant applications in App Engine

After creating a multitenant application on Google App Engine with Django Rest Framework and Angular Front end, I'm looking to map multiple domain names to different resources within the platform. Currently, I have only configured one domain name but ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Creating an interface for React props

Hey everyone, I'm facing an issue and need some advice. I prefer using interfaces to maintain readability and utilize intellisense in my code. However, I'm struggling with implementing this approach when working with data passed through props. H ...

Is there a way to mock a "find" call in mockingoose without getting back "undefined"?

I am currently working with mockingoose 2.13.2 and mongoose 5.12.2, leveraging Typescript and jest for testing purposes. Within my test scenario, I am attempting to mock a call to my schema's find method. Here is what I have tried: import mockingoose ...

Encountering a compilation error when attempting to run ng serve in Angular, resulting in a failed build and

I am a beginner in using Angular and I recently downloaded a git repository. When trying to run the application, I encountered an error as shown below. If anyone can provide assistance, it would be greatly appreciated. Thank you in advance. I have attempt ...

Create a system for detecting changes in simple input elements and triggering a function to update the final result

There are a maximum of 12 inputs that represent the same entities or objects but with varying integer values. These values directly impact the final result displayed to the user. Whenever any of the input values change, a function needs to be triggered to ...

Nodejs version 0.11 is encountering difficulties in enabling native extensions for websockets

After updating my node to version v0.11.4, I encountered an issue with building the naive extension when running npm install websocket. The error output at the top is as follows. Has anyone else faced this problem? <pre></p> <blockquote&g ...