RxJs get the value from the observed

In component:

singleEvent$: Observable<Event>; 

In init, I get observable

 this.singleEvent$ = this._eventService.events$ .map(function (events) { let eventObject = events.find(item => item.id === eventid); let eventClass: Event = new Event(eventObject); return eventClass; }); 

How can I take the current value, for example event.name ?

+21
angular typescript observable rxjs
source share
2 answers

To get data from the observed, you need to subscribe:

 this.singleEvents$.subscribe(event => this.event = event); 

In the template, you can directly link the observed objects using an asynchronous channel :

 {{singleEvents$ | async}} 
+38
source share

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); } }); } } 
+5
source share

All Articles