My apologies if this is posted somewhere on Stack Overflow, but I'm not finding a answer that works for me.
I have a BehaviorSubject that tracks a state as a boolean value. I also have a public getter method that is an Observable that returns the BehaviorSubject. I do this so that not only can I subscribe to changes in the BehaviorSubject value, but to also get the current value when it hasn't changed. While I'm able to get the proper value from subscribe, I am getting an Object returned when just calling the getter. I want it to return the last value.
I've tried using .getValue(), which does not seem to work, and I've tried .value, which does seem to work but throws an error in the IDE.
I've created a very basic example of what I'm trying to accomplish and I've put comments in the my.service.ts file to show what I'm going for. Please advise. Thank you!
EDIT: I used what was in stack blitz by default and assigned the getter to the name variable just to see it. My goal is to get the value so that I can do something based on wether the value is true or false. I'm sure I'm missing something really simple.
EDIT: Adding code to question as requested
EDIT: I've also added the .subscribe to show that while I understand that's how Observables work, I also want to check the value OUTSIDE of a value change using the same getter if it is possible.
MyService
import { Observable, BehaviorSubject } from "rxjs";
export class MyService {
constructor() {}
private _isBoolean = new BehaviorSubject<boolean>(false);
public get isBoolean(): Observable<boolean> {
//return this._isBoolean.value; // Returns boolean, but throws error "Type 'boolean' is not assignable to type 'Observable<boolean>'."
return this._isBoolean; // Returns object, but I want the value
}
}
AppComponent
import { Component } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name;
constructor(private _myservice: MyService) {
this._myservice.isBoolean.subscribe(val => {
console.log("value from subscribe: " + val)
})
this.name = this._myservice.isBoolean;
if (this._myservice.isBoolean) {
console.log("true!");
} else if (!this._myservice.isBoolean) {
console.log("false!");
}
}
}
this._isBoolean.getValue()
on MyService, then it will work. - Derek WangBehaviorSubject.getValue()
- Derek Wang