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?