RxJs 从 observable 获取价值

RxJs get value from observable

在组件中:

singleEvent$: Observable<Event>;

在初始化时,我可以观察到

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

我怎样才能像 event.name 这样获取当前值?

要从 observable 获取数据,您需要订阅:

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

在模板中,您可以使用 async pipe:

直接绑定到 observables
{{singleEvents$ | async}}

为了补充 Günter Zöbauer 的回答,如果您希望同步获取 Observable 中的值,BehaviorSubject 可能就是您正在寻找的。

BehaviorSubject 是一个始终有值的 Observable,您可以调用 myBehaviorSubject.getValue()myBehaviorSubject.value 来同步检索 BehaviorSubject 当前持有的值。

由于它本身也是一个可观察对象,您仍然可以订阅 BehaviorSubject 以异步响应它所持有的值的变化(例如 myBehaviorSubject.subscribe(event => { this.event = event }))并在您的组件模板中使用异步管道(例如 {{ myBehaviorSubject | async }}).

这里有一些用法来匹配你给定的例子,从给定的服务在你的组件中创建一个 BehaviorSubject:

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

您可以使用 observable.pipe(take(1)).subscribe 将 observable 限制为仅获取一个值并停止监听更多。

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

添加@ZackDeRose 在@Günter Zöchbauer 回复中添加的内容

private beneficiary = new BehaviorSubject<__IBeneficiary>(newBeneficiary);
beneficiary$ = this.beneficiary.asObservable();

setBeneficiaryInfo(beneficiary: __IBeneficiary): void {
    this.beneficiary.next(beneficiary);
    // when your you subscribe to beneficiary$ you would get the new value
}

/* when implementing in component or other function
   this.beneficiary$.subscribe(
        item => {
            // use current value
        }
    );
*/

modePersonalInformation(personalInfo, mode: string): Observable<any> {
    const $beneficiary = this.beneficiary.value; 
    // this will get the current observable value without the subscrib callback function
    return this.http.post<any>(
        `${this.apiURL}/${mode}-biography/personal` + ((mode === 'update' && $beneficiary?.id) ? `/${$beneficiary.id}` : ''),
        {...personalInfo},
        this.httpOptions
    )
}

您必须添加一些条件来检查您是否要使用现有对象