RxJs get value from observable

前端 未结 3 1665
盖世英雄少女心
盖世英雄少女心 2020-12-06 03:58

In component :

singleEvent$: Observable;

On init, I get observable

this.singleEvent$ = this._eventService.even         


        
3条回答
  •  有刺的猬
    2020-12-06 04:51

    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;
    
      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);
            }
          });
      }
    }
    

提交回复
热议问题