Passing objects in Angular2 through a service

In my project, there are certain components that rely on previous steps being completed before they can proceed to the next step.

To streamline the process of toggling a status indicator, I attempted to implement a function in a shared service file.

Service:

// Loading indicator
private isLoading = {
    enabled: false,
    step: null
};

/**
 * Set the status for our loading indicator
 *
 * @param isLoading
 * @param step
 */
setLoader(isLoading, step) {
    this.isLoading = {
        enabled: isLoading,
        step: step
    };
    console.log(this.isLoading);
}

A component:

this._massEmpService.setLoader(true, 'step2');

HTML:

<div *ngIf="isLoading?.enabled && isLoading?.step == 'step2'" class="loader" align="center">
  <img src="images/loading-bars.svg" alt="" />
</div>

Although the function is triggered correctly when the button in one component is clicked and the object is printed as expected, the HTML in another component does not reflect this status change.

Is it possible that data cannot be passed through a service in this manner?

Answer №1

The display is not refreshed because the function ApplicationRef.tick() was not invoked.

There are two methods to enhance this:

1. Use observables in your service

A possible implementation would look like this:

service.ts

import {Observable, BehaviorSubject} from 'rxjs';

export class Service {

    public isEnabled: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();
    public step: BehaviorSubject<number> = new BehaviorSubject<number>();

    setLoader(isLoading, step) {
         this.isLoading = {
              enabled: isLoading,
              step: step
         };

         this.isEnabled.next(this.isLoading.enabled);
         this.step.next(this.isLoading.step);
         console.log(this.isLoading);
    }
}

component.ts:

@Component({})
export class Component {
     public isEnabled: Observable<boolean> = this.service.isEnabled;
     public step: Observable<number> = this.service.step;
}

component.html:

<div *ngIf="(isEnabled | async) && (step == 'step2' | async)" class="loader" align="center">
  <img src="images/loading-bars.svg" alt="" />
</div>

2. Manually trigger view update

You can do it like this:

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

export class Service {
     constructor(private appRef: ApplicationRef) {}
     setLoader(isLoading, step) {
          this.isLoading = {
               enabled: isLoading,
               step: step
          };
          console.log(this.isLoading);
          this.appRef.tick();
     }
}

Learn more about ApplicationRef here: https://angular.io/api/core/ApplicationRef

The choice depends on your specific requirements and preferences.

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

What sets apart obj.prop from obj['prop'] in typescript?

After utilizing @babel/parser to parse a string and receiving an AST, I am encountering an error when logging the AST by using the type of obj.prop. However, it works when using the type of obj['prop'] import { parse } from "@babel/parser&qu ...

What is the significance of a TypeScript import that starts with a # symbol?

While reviewing some TypeScript code, I came across the following import: import { URLS } from '#constants'; This seems to be a different way of writing: import { URLS } from './constants'; I'm curious about the significance of t ...

What is the recommended way to handle data upon retrieval from a Trino database?

My goal is to retrieve data from a Trino database. Upon sending my initial query to the database, I receive a NextURI. Subsequently, in a while loop, I check the NextURI to obtain portions of the data until the Trino connection completes sending the entire ...

assign data points to Chart.js

I have written a piece of code that counts the occurrences of each date in an array: let month = []; let current; let count = 0; chartDates = chartDates.sort() for (var i = 0; i < chartDates.length; i++) { month.push(chartDates[i].split('-&ap ...

Is there a way I can utilize the $timeout and $interval functionalities that were implemented in angular.js, but for the Angular framework?

When working with Angular.js, I made use of the $timeout and $interval functions (which are similar to setInterval and setTimeout in JavaScript). $timeout(function(){}) $interval(function(){},5000) To stop the interval, I utilized $interval.cancel($scop ...

TypeScript code to transform an array of strings into a custom object

I have a specific requirement that I have partially achieved using Java, but now I need to transition it to TypeScript on the client side. Please note: The input provided below is for illustrative purposes and may vary dynamically. Input: var input = [" ...

How to extract a string value from an observable array in Angular2 NativeScript?

I inserted JSON data into an observable array. My goal is to extract only the address from ShowData, specifically as a string value based on its position. ShowData.ts: class ShowData{ constructor(public id:number, public name:string, public address:s ...

Using TypeScript and Node.js with Express; I encountered an issue where it was not possible to set a class property of a controller using

I have a Node application using Express that incorporates TypeScript with Babel. Recently, I attempted to create a UserController which includes a private property called _user: User and initialize it within the class constructor. However, every time I ru ...

Having difficulty disassociating the radio button from the label

<div class="questions" style="font-size:13pt;margin-left:20px;margin-bottom:10px;"> <p class="question" id="ques{{i+1}}" style="font-size:17pt;font-weight:normal">{{i+1+". "+a.question}}</p> <img *ngIf="isImage[i]" [src]="a.image" ...

Managing the state of radio buttons in React using Typescript

I'm currently working on a signup page using React Typescript. I am facing an issue with setting the gender using radio buttons, storing it in the state, and sending it to the server. However, the toggle feature is not working as expected. Do you have ...

Is there a way to include two objects in an Angular2 post request?

This piece of code is giving me trouble: On the client side (using Angular 2) saveConfig(configType: ConfigTypes, gasConfigModel: GasConfigModel): any { console.info("sending post request"); let headers = new Headers({ 'Content-Type& ...

Unable to access NgForm.value in ngAfterViewInit phase

In my template driven form, I need to save the initial values of controls. Initially, I thought that using the ngAfterViewInit method would be ideal since it is called after the template is rendered, allowing me to access and store the value of form contro ...

Using TypeScript to maintain the context of class methods as event handlers within the "this" instance

I'm facing a challenge with TypeScript Classes where I constantly need to use Function.bind() to link HTML Element events to the current instance. class VideoAdProgressTracker extends EventDispatcher { private _video:HTMLVideoElement; constr ...

Is it feasible to obtain the opposite result of a router guard in Angular?

I am developing an Angular application that utilizes Okta for authentication. I have specific pages where I only want to permit access if the user is not authenticated. Despite not finding any built-in guards or functions in the current version of the Okta ...

Guide on using automapper in typescript to map a complex object to a "Map" or "Record" interface

I have been utilizing the automapper-ts with typescript plugin for automatic mapping. Check it out here While it works smoothly for simple objects, I encountered issues when dealing with complex ones like: Record<string, any> or Map<string, Anoth ...

Create a conditional event callback in TypeScript for React

How can I specify an optional callback for Events in a React Typescript component? interface Props{ data: any handleClick?: ()=>void } const FunctionalComponent: React.StatelessComponent<Props> = (props) => { return ( < ...

What is the process for accessing a different view and its features on a separate screen using Angular portal?

In my angular project, I have multiple components. One component is being looped with an array using the following code: <body-chart *ngFor="..."></body-chart> Within the body-chart component : <div> <canvas id="canv ...

Is there a way to refresh the list automatically after deleting an item using Firebase?

When I use ngFor on a list to display multiple recordings in a table, I have two methods in my TypeScript file - one for getAll and another for delete, as shown below: HTML: <tr *ngFor="let value of imagesList"> <td scope="row& ...

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Troubleshooting a Missing Angular (8) Pipe Error in Your Ionic 4 Application

Despite seeing similar questions posted here, none have provided a solution to my issue. I believe I am implementing it correctly, but clearly something is not right. In the app I'm developing with Ionic 4, I need to add a key to a URL in a gallery. ...