Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me.

References:

Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components

Despite attempting the logic outlined in the references above, I've encountered difficulties with its implementation

Below is the HTML binding for Angular Material:

<mat-progress-bar mode="indeterminate" *ngIf="commonViewModel.showProgressBar()"></mat-progress-bar>

Parent Component:

export class AppComponent {
constructor(public commonViewModel: CommonViewModel) {    }
ngOnInit() {
        this.isLoading();
    }
isLoading() {
        console.log("app=" + this.commonViewModel.showProgressBar());
        return this.commonViewModel.showProgressBar();
    }
}

Child Component:

export class HomeComponent {
    private GetHomeItemUrl: string = "Home/GetHomeItem";
    private _homeItemService: GenericHttpClientService;
    constructor(public commonViewModel: CommonViewModel) {
        this.getHomeItemHttpCall();
    }

    private getHomeItemHttpCall(): void {

        this.commonViewModel.setProgressBarShow = true;
        this._homeItemService.GenericHttpGet<GenericResponseObject<HomeViewModel>>(this.GetHomeItemUrl).subscribe(data => {
            if (data.isSuccess) {
                this.commonViewModel.setProgressBarShow = false;
                console.log("home=" +this.commonViewModel.showProgressBar());
            }

        }, error => {
            console.log(error);
        });
    }
}

This is my service class which holds the value as true and false

@Injectable()
export class CommonViewModel {
    progressBarShow: boolean = true;

    public showProgressBar(): boolean {
        return this.getProgressBarShow;
    }

    set setProgressBarShow(flag: boolean) {
        this.progressBarShow = flag;
    }
    get getProgressBarShow(): boolean {
        return this.progressBarShow;
    }
}

The console output

https://i.sstatic.net/6vhRA.png

Even though the console displays both True and False, the app never hides because the app component's value remains true

I am seeking guidance on where I might be going wrong. I prefer not to use Input and Output for sharing data.

Please advise on how I can resolve this issue.

Answer №1

It is likely that your parent component and child component are receiving two separate instances of the service due to where it is being provided. Consider providing the service from your app module to ensure they are using the same instance.

If the child component is a direct child of the parent, you may not need the service at all. Instead, consider using an EventEmitter (via @Output) in the child component to facilitate communication between them.

For more information, refer to the documentation available at https://angular.io/api/core/EventEmitter

Answer №2

In my opinion, the answer provided by GSSWain should do the trick. If not, you can also try using a getter method.

<mat-progress-bar *ngIf="isLoading"></mat-progress-bar>

get isLoading(){
    return this.commonViewModel.showProgressBar();
}

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

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

React component state change in reverse

As I work on a simple login form component, I encountered an issue where clicking on the form should make it disappear and only display my JSON data. However, due to my limited experience with React state management, I seem to be achieving the opposite eff ...

Updating Arrays in Node.js isn't happening as expected

Hello, I have a function that I am calling from my controller like this: var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id); but the controller is returning an empty array as a result. However, when I log the result in my model, ...

Securing important code sections in Node/Express using Typescript: A guide

I'm fairly new to the world of JavaScript/Typescript/Node/Express, and as I've been researching, it seems there isn't a universally accepted method for locking critical sections of code in a Node/Express application. I've come across a ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Unit testing Jest for TypeScript files within a module or namespace

Recently, I've joined a mvc.net project that utilizes typescript on the frontend. There are numerous typescript files wrapped within module Foo {...}, with Foo representing the primary module or namespace. All these typescript files are transpiled in ...

Animation effects compatible with iOS devices are professionally crafted using CSS

I just implemented a custom hamburger menu with animation using HTML, CSS, and JavaScript on my website. The animation works perfectly on Android devices but not on iOS. Any suggestions for fixing this issue? I attempted to add the Webkit prefix to each p ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

An event change leads to the activation of another event

I've set up some input fields and linked their values to a JavaScript variable. Strangely, the drinkInput value always shows up as blank for some reason. When the typeInput event is triggered, its value prints correctly in the console followed by an e ...

The Azure Application Insights internal error message "Required field specification missing: 24" was encountered

I recently integrated the front-end Azure application insights to monitor events on my application. The frontend of my application is built using web-pack. However, I encountered an issue where no events were being tracked when using the NPM setup, but eve ...

Event delay with JavaScript and jQuery

In my WordPress (WooCommerce) website, I am working on creating a quantity field... It is functioning properly; however, I want to trigger an event when the + or - buttons next to Quantity are pressed in order to "Update cart". This is what I have tried: ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

Tips for invoking a JavaScript function within an iframe

I'm looking to add an iframe to my HTML document, but I also need to pass a variable from a JavaScript function that is located on the same page (which retrieves cookie values). <script type=text/JavaScript> var generateLinkerUrl = function(url ...

The issue of drop shadows causing links to not work properly in Internet Explorer

I am currently working on a website design that features a fixed menu positioned behind the body. When the menu icon is clicked, some jQuery code shifts the body to the left. To create the effect of the fixed menu being positioned underneath, I have added ...

JavaScript PIP video feature

Currently, I am utilizing the requestPictureInPicture function to display the HTML video element in a popup window. However, I have encountered an issue where the size is restricted to approximately 920 x 540 when in Picture-in-Picture mode. I am wonderin ...

Having issues getting Angular up and running

I'm having some issues with the global installation of Angular. Below is the error message I received: C:\Users\DevSa\ng -> C:\Users\DevSa\node_modules\@angular\cli\bin\ng > @angular/<a href ...

Implement a universal Custom Validator to be applied to all FormControls across the entire application

We've encountered a scenario where a client proposed incorporating a custom validator to every field in their application, which comprises of over 1000 Angular formControls. I'm curious to know if there exists a method to universally alter the f ...

Navigating Unknown Properties in Angular: A Guide to Iterating Through Arrays

I'm having trouble coming up with a title for my question. I want to loop through an array of dynamic objects coming from a database, but I don't know the properties of the objects. Here's an example of the array object: [{ "id": 9, ...

Tips on retaining information across postbacks using view state in C# ASP.NET

I need help with an issue I'm facing while creating a 100-question online test. Each question has four radio buttons (options), and I want the browser to remember the selected values of each question when I press the submit button. I am trying to retr ...

Exploring the retrieval of data from .find within a JSON object using Node.js

In my custom database setup, which mirrors a collection in MongoDB containing JSON objects. export const roles = [ { _id: "870c4350-3cf5-4f35-8429-513bd86c6734", programId: "e3e20d57-571d-45ab-b13a-b07d29fcf968", profileId: "3cbaadcf-41e1-42 ...