在组件中:
singleEvent$: Observable<Event>;
在init上,我得到了可观察的
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
?
答案 0 :(得分:36)
要从observable获取数据,您需要订阅:
this.singleEvents$.subscribe(event => this.event = event);
在模板中,您可以使用| async
管道直接绑定到observable:
{{singleEvents$ | async}}
答案 1 :(得分:5)
要添加到GünterZöbauer的答案,如果您希望同步获取Observable中的值,可以使用BehaviorSubject。
BehaviorSubject是一个始终具有值的Observable,您可以调用myBehaviorSubject.getValue()
或myBehaviorSubject.value
来同步检索BehaviorSubject当前持有的值。
因为它本身也是一个可观察的,你仍然可以订阅BehaviorSubject以异步地对它所拥有的值的变化作出反应(例如myBehaviorSubject.subscribe(event => { this.event = event })
)并在组件的模板中使用异步管道(例如{ {1}})。
以下是一些用于匹配您给定示例的用法,以便从给定服务在组件中创建BehaviorSubject:
{{ myBehaviorSubject | async }}
答案 2 :(得分:3)
您可以使用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
答案 3 :(得分:0)
添加@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
)
}
您必须放置一些条件来检查是否要使用现有对象