To add to Gunter Zobauer's answer, a BehaviorSubject may be what you are looking for if you want to get the value inside your Observable synchronously.
BehaviorSubject is an Observable that always has a value, and you can call myBehaviorSubject.getValue() or myBehaviorSubject.value to synchronously get the value that BehaviorSubject currently contains.
Since it itself is also observable, you can still subscribe to BehaviorSubject to asynchronously respond to changes in the value that it contains (for example, myBehaviorSubject.subscribe(event => { this.event = event }) ) and use asynchronous channel in the component template (for example, {{ myBehaviorSubject | async }} .
Here are some examples of using your example to create a BehaviorSubject in your component from this 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); } }); } }
ZackDeRose
source share