To add on to Günter Zöbauer's answer, a BehaviorSubject may be what you are looking for if you're looking to synchronously get the value inside of your Observable.
A BehaviorSubject is an Observable that always has a value, and you can call myBehaviorSubject.getValue()
or myBehaviorSubject.value
to synchronously retrieve the value the BehaviorSubject currently holds.
Since it is itself an observable as well, you can still subscribe to the BehaviorSubject to asynchronously react to changes in the value that it holds (e.g. myBehaviorSubject.subscribe(event => { this.event = event })
) and use the async pipe in your component's template (e.g. {{ myBehaviorSubject | async }}
).
Here's some usage to match your given example to create a BehaviorSubject in your component from the given service:
@Component({
//...
})
export class YourComponent implements OnInit {
singleEvent$: BehaviorSubject<Event>;
constructor(private eventService: EventService){}
ngOnInit(){
const eventid = 'id'; // <-- actual id could go here
this.eventService.events$
.pipe(
map(events => {
let eventObject = events.find(item => item.id === eventid);
let eventClass: Event = new Event(eventObject);
return eventClass;
})
)
.subscribe(event => {
if(!this.singleEvent$){
this.singleEvent$ = new BehaviorSubject(event);
} else {
this.singleEvent$.next(event);
}
});
}
}