typescript RxJ从可观察性中获得价值

6rvt4ljy  于 2023-01-31  发布在  TypeScript
关注(0)|答案(5)|浏览(162)

在组件中:

singleEvent$: Observable<Event>;

在init中,我得到了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;
  });

如何获取当前值,例如event.name

prdp8dxp

prdp8dxp1#

要从可观察对象获取数据,您需要订阅:

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

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

{{singleEvents$ | async}}
ijnw1ujt

ijnw1ujt2#

为了补充君特·佐鲍尔的回答,如果你希望同步地获得你的可观察对象内部的价值,那么行为主体可能就是你正在寻找的。
BehaviorSubject是一个Observable,它总是有一个值,您可以调用myBehaviorSubject.getValue()myBehaviorSubject.value来同步检索BehaviorSubject当前持有的值。
因为它本身也是一个可观察对象,所以您仍然可以订阅BehaviorSubject,以便异步地对它所持有的值的变化做出React(例如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);
        }
      });
  }
}
polkgigr

polkgigr3#

您可以使用observable.pipe(take(1)).subscribe来限制可观察性,使其仅获得一个值,而不再侦听更多值。

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
fkaflof6

fkaflof64#

加上@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
    )
}

你必须设置一些条件来检查你是否想使用一个已有的对象

ddhy6vgd

ddhy6vgd5#

我不想这么说,但这些都是错误的答案。如果它存在,你可以很容易地通过使用,
此._事件服务.事件$.源[“_值”]
并从对象中获取任何你想要的值。源代码已被弃用,但仍然有效。

相关问题