Angular 4: Dealing with undefined returns from Observables

Let's start off by clarifying that this situation does not involve an http request. Instead, it's a much simpler scenario where one component sets a boolean value and another component displays or hides an element based on it.

The issue at hand is that the second component always receives 'undefined' in the subscribe callback. Surprisingly, when I had the main component also subscribe, it received the value correctly.

Below is the relevant code snippet:

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

@Injectable()
export class EnablerService {
  private _enabled= new Subject<boolean>();
  get Enabled() { return this._enabled.asObservable(); }
  SetEnabled(value: boolean) {
    this._enabled.next(value);
    console.log(`service: ${value}`);
  }
}

Main component:

import { Component } from '@angular/core';
import {EnablerService} from './enabler.service';

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

export class AppComponent {
  title = 'app';
  private _isEnabled: boolean;
  constructor(public service: EnablerService) {
    service.Enabled.subscribe(val => {
         this._isEnabled = val; 
         console.log(`app comp: ${this._isEnabled}`); 
    });
  }

  Switch() {
    this.service.SetEnabled(!this._isEnabled);
    console.log('switched');
  }
}

Other component:

import { Component, OnInit } from '@angular/core';
import {EnablerService} from './enabler.service';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css'],
  providers: [EnablerService]
})
export class FooterComponent implements OnInit {
  private _isEnabled: boolean;
  constructor(private service: EnablerService) {
    this._isEnabled = true;
  }

  ngOnInit() {
    this.service.Enabled.subscribe(val => {
      this._isEnabled = val; // this one here.
      console.log(`footer comp: ${this._isEnabled}`);
    });
  }

}

In the main component, the Switch method is bound to a button and it functions correctly. Upon clicking, the console displays:

app comp: true

service: true

switched

undefined

Clicking again toggles the values from true to false, but still presents 'undefined' as output.

Does anyone have insight into what might be causing this issue?

Answer №1

By placing your EnablerService in the component's providers array, a new instance of the service is created each time. To ensure a single instance is shared between components, you should provide the EnablerService in a parent component, such as the AppRoot component, and then inject it into child components.

For an example of this practice, refer to the documentation: only the MissionControlComponent has MissionService listed in providers, while the AstronautComponent simply injects it.

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 is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

What is the process for integrating tsconfig.json into a production build?

Within my tsconfig.json file, I have set "resolveJsonModule": true. Running npm run webpack:dev locally results in a smooth app start-up. However, when I try to execute npm run webpack:prod, it fails with the error message: '--resolveJsonModule&apos ...

What are the best practices for utilizing fetch() to retrieve data from a web API effectively?

Is there a way to store stock data in stockData and display it in the console upon form submission? Upon submitting the form, I only receive undefined. I suspect this may be due to a delay in fetching data from the API (but not certain). How can I resol ...

What purposes do the different files within an Angular bundle serve during AoT compilation?

After running the command ng build --prod --aot in my Angular 4 project, I found the following files in my dist folder. inline.6405cab307cfc3c6a636.bundle.js : 2 KB main.a799c9fd4322567743dc.bundle.js : 35 KB polyfills.b72d4efc376613f94934.bu ...

What styling options are available in the Angular 6 build configuration for style.js?

Upon inspecting the HTML source code of my single-page application built with Angular 6 using SASS, I stumbled upon this list of files: <script type="text/javascript" src="runtime.js"></script> <script type="text/javascript" src="polyfill ...

Unable to create a connection to the server using websockets

Currently, I am working on a MEAN stack application. The communication between the client and server is handled through a combination of HTTP requests and websockets. Everything operates smoothly when running the application on localhost. However, upon at ...

How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet: const Locales = { en_gb: 'en-gb', en_us: 'en-us', } as const type ApiLocales = typeof Locales[keyof typeof Locales] type DatabaseLocales = keyof typeof Locales function databaseLanguage ...

Steps to resolve security vulnerabilities found in Angular 12.0.3 through npm audit

Upon creating a fresh Angular 12.0.3 project, running npm audit immediately uncovers 8 high and 40 moderate vulnerabilities. # npm audit report css-what <5.0.1 Severity: high Denial of Service - https://npmjs.com/advisories/1754 fix available via `npm ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Issue with Angular 2: Unable to connect to 'model' as it is not recognized as a valid property of 'p-steps'

I've been struggling to run the code below: states.component.html <p-steps [model]="items"></p-steps> import { Component, OnInit } from '@angular/core'; import { StepsModule, MenuItem } from 'primeng/primeng'; impo ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

Troubleshoot TypeScript API within Angular 12 using Chrome debugger

I'm having trouble finding a solution on SO. Can anyone help me debug and check the code snippet below for hello? getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10); this.heroService.getHero(id) .sub ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...

The deployment of the remix is unsuccessful in Vercel, even though it functions perfectly during development. The error message states that 'AbortController' is not

I'm new to React and could use some assistance with a deployment issue on Vercel. Any ideas on why this is failing? I haven't explicitly used AbortController anywhere, so I'm suspecting it might be related to one of the installed packages? ...

What causes the form to consistently show as invalid once it has been submitted?

register.html : <form [formGroup]="signupForm" (submit)="onSubmit()" class="form-detail"> <h2>Registration Form</h2> <div class="form-row-total"> <div class="form-row"> <in ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

The call stack has exceeded its maximum size in Angular Single SPA, resulting in an error

Encountering an issue while running npm run build for a single spa application. I recently converted this angular application into single-spa and upgraded the angular version to 10.2.5: https://i.stack.imgur.com/qIHMf.png https://i.stack.imgur.com/adSTB. ...

Dealing with Endless Loops in React TypeScript: What Happens When State is Set in Multiple Instances of the Same

I'm currently facing an issue where I have two instances of the same component being rendered: <div><Modal title='Login'/></div> <div><Modal title='Join'/></div> Within the component, based on ...

There seems to be an issue with the compatibility between typescript and the current version (4.17.14) of the express-serve-static

Using "@types/express-serve-static-core": "4.17.13", the augmentation of express-serve-static-core is functioning properly: import { Request, Response, NextFunction } from 'express' import { PrismaClient } from '@prisma/c ...

Issue encountered while loading ng2-bootstrap

Encountering an issue with importing ng2-bootstrap. Here is the error message: http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js 404 (Not Found) Error: Error: XHR error (404 Not Found) loading http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js at ...