How can I get the current value from an Observable without subscribing to it? I just want the current value one time and not new values as they are coming in.
You need to use BehaviorSubject,
- BehaviorSubject is similar to ReplaySubject except it only remembers the last publication.
- BehaviorSubject also requires you to provide it a default value of T. This means that all subscribers will receive a value immediately (unless it is already completed).
It will give you the most recent value published by the Observable.
BehaviorSubject provides a getter
property named value
to get the most recent value passed through it.
//Declare a Subject, you'll need to provide a default value.
const subject: BehaviorSubject<string> = new BehaviorSubject("a");
USAGE:
console.log(subject.value); // will print the current value
In case you want to conceal your BehaviorSubject and only expose it's value, let's say from a Service, you can use a getter like this.
export class YourService {
private subject = new BehaviorSubject('random');
public get subjectValue() {
return this.subject.value;
}
}