How do I verify if a boolean variable has been changed within an Angular service?

In my MatHorizontalStepper parent component, I utilize the subscribe function to monitor changes in an Observable within a service. The purpose is to automatically progress to the next step in the stepper when the observable switches from false to true.

Despite my efforts, I am encountering difficulties with updating the step correctly. Here are the two components I have implemented:

Parent Component

import { Component, OnInit, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { MatHorizontalStepper } from '@angular/material';
import 'rxjs/observable/of';

// Services
import { StepperService } from './services/stepper.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: './app.component.css'
})

    export class AppComponent implements OnInit {

      @ViewChild('stepper') mainStepper: MatHorizontalStepper;

      constructor(
        private stepperService: StepperService
      ) { }

      ngOnInit() {
        console.log('Migration Service launched.');
        this.stepperService.stageOne.subscribe((result) => {
          if (result) {
            console.log('Moving to stage 2.');
            this.mainStepper.selectedIndex = 1;
          }
        });

      }

    }

Service

The service monitors the completion of a form within a component by utilizing formComplete to update the appropriate stage.

import { Injectable, OnChanges, SimpleChanges, ViewChild } from '@angular/core';
import { MatHorizontalStepper } from '@angular/material/stepper';
import { FormGroup } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import 'rxjs/observable/of';

export class StepperService {
  @ViewChild('stepper') stepper: MatHorizontalStepper;

  // A stage can be incomplete (false) or complete (true).
  stageOne: Observable<boolean> = Observable.of(false);

  // Function accepts FormGroup from another component
  formComplete(receivedForm: FormGroup, receivedStepper: MatHorizontalStepper) {
    if (receivedForm.status === 'VALID') {
      switch (receivedStepper.selectedIndex) {
        case 1:
          this.stageOne = Observable.of(true);
          console.log('Stage one complete.');
          break;

        default:
          break;
      }
    }
  }

}

What steps should I take to ensure that the parent component captures the updated status of the observable in the service?

Answer №1

The stageOne Observable consistently emits only false:

 Observable.of(false)

generates an observable that emits false upon subscription and then completes immediately.

In the code snippet below:

this.stageOne = Observable.of(true);

the observable does not emit anything. Instead, it substitutes the original observable with a new one. Since the initial observable completes promptly after subscription, any subsequent operations are ineffective as the component is already unsubscribed. Even if it remained subscribed, the new observable was never accessed.

To have control over when an observable emits values, utilize a Subject:

stageOne = new Subject<boolean>();

[...]

this.stageOne.next(true);

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

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

Updating directives is required when there is a modification in the input

I created a custom directive that controls the opacity of an element based on an input value: import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Dir ...

Encountered an issue while resolving dependency tree for angular tslib

When running npm install, I encountered the error shown in this image: https://i.stack.imgur.com/PInQE.png The CLI version is Angular CLI: 9.1.8. Any assistance would be greatly appreciated. Thank you! ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Issue encountered: In Angular 8, an error is thrown stating "TypeError: Object(...) is not a function" when trying to utilize ng-idle/ng-keepalive within the eval

I've been attempting to incorporate ng-idle/ng-keepalive into my Angular 8 project, but no matter how many versions I install, the console keeps showing me this same error: Error: Uncaught (in promise): TypeError: Object(...) is not a function TypeEr ...

Having trouble generating a bin executable for my npm package

Referencing: https://docs.npmjs.com/cli/v10/configuring-npm/package-json#bin I am attempting to generate a "binary" for my npm package. The structure of my package.json is as follows: { "name": "@internal/my-exe", "version": "0.0.0", "type": "commo ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

The error message "Angular 4 does not recognize the 'dragula' property as a valid property of the 'div' element" is displayed

Struggling to integrate ng2-dragula with the AspNetCore SPA template. Despite trying various solutions, I am still encountering the following error: Exception: Call to Node module failed with error: Error: Template parse errors: Can't bind to 'd ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

I'm having trouble installing node-sass and encountering an error. Can anyone offer advice on how to resolve this issue?

Encountering an error while trying to install node-sass, can someone assist me in resolving this issue? npm ERR! code EPERM npm ERR! syscall rename npm ERR! path C:\Users\deepe\OneDrive\Documents\Yajnaseni\POC\language&bs ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Error: The term 'makeStyles' cannot be found in the '@material-ui/core' module after installing Material-ui-pickers

Can anyone help me with using the inlineDatePicker components from Material UI pickers? I found them here: After running the npm -i command, I encountered an error during compilation: Failed to compile. ./node_modules/material-ui-pickers/dist/material-u ...

What is the best way to send data to the ng2-smart-table renderComponent using an HTTP request?

I am working with a table that includes a custom component in one of its cells. There is also a service that provides the data to display in this table. The custom component I have implemented includes a select feature, so the column in the table looks lik ...

Confirm that the dependency has been invoked using Sinon

I am currently working on testing whether a dependency has been called or not. Here is an example of my code: export default class vehicle { private builder: CarBuilder; constructor() { this.builder = CreateCar(); <- factory return fake data } crea ...

Can auto-import be configured in WebStorm without using double dots?

Is it feasible to configure WebStorm for automatic import of modules/Component/components/MyComponent instead of using ../MyComponent? ...

Problem encountered during NextJS build: ReferenceError - 'window' is undefined

While I am in the process of developing my app, I have encountered a perplexing issue with a ReferenceError: window is not defined. This error seems to be happening even though I am utilizing 'use client' "use client"; import React, { u ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

Is it Better to Perform Manual Change Detection in AngularJS or Angular 2?

My issue involves working with a sizable data list where each element has a filter applied. In order to optimize performance due to potentially adding numerous attributes to each entry, I seek to update the list only when there is a change in the data (eve ...

Building a personalized radio button Angular component for optimal integration with ReactiveForms

I have developed a custom radio button that stores the current value in the model attribute and checks if the model and value are equal in terms of styling. Everything functions smoothly when using template forms with the [(ngModel)] attribute on the tag. ...