RxJs get value from observable

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

In component :

singleEvent$: Observable;

On init, I get observable

this.singleEvent$ = this._eventService.even         


        
相关标签:
3条回答
  • 2020-12-06 04:30

    To get data from an observable, you need to subscribe:

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

    In the template you can directly bind to observables using the async pipe:

    {{singleEvents$ | async}}
    
    0 讨论(0)
  • 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<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);
            }
          });
      }
    }
    
    0 讨论(0)
  • 2020-12-06 04:51

    You can use observable.pipe(take(1)).subscribe to limit the observable to get only one value and stop listening for more.

    let firstName: string; 
    
            this.insureFirstName
                .pipe(take(1))  //this will limit the observable to only one value
                .subscribe((firstName: string) => {
                    this.firstName = firstName; asssgning value 
                });
            console.log(this.firstName); //accessing the value
    
    0 讨论(0)
提交回复
热议问题