是的,您可以像使用 Promises 一样使用 Observables:
async asyncAddEmployeeData(): Promise<any> {
return this.apiService.getEmployeeDataObservable()
.pipe(
mergeMap(employeeData => this.apiService.getParamsObservable()
.pipe(
tap((paramsData): void => {
// There is available data
// from apiService.getEmployeeDataObservable()
// as employeeData variable
// and data from apiService.getParamsObservable()
// as paramsData.
// You can do in tap function all the same
// as in next in the subscribe.
}),
)
),
)
.toPromise();
}
并像这里一样使用它:
async ngOnInit(): Promise<void> {
// ngOnInit just for example.
const someVariable = await this.asyncAddEmployeeData();
}
但是使用 Observable 的常规方式是这样的:
addEmployeeData(): Observable<any> {
return this.apiService.getEmployeeDataObservable()
.pipe(
mergeMap(employeeData => this.apiService.getParamsObservable()
.pipe(
tap(paramsData => {
// There is available data
// from apiService.getEmployeeDataObservable()
// as employeeData variable
// and data from apiService.getParamsObservable()
// as paramsData.
}),
)
),
take(1), // Just if you need only first value, if not, please, remove this string.
);
}
和订阅:
ngOnInit(): void {
// ngOnInit just for example.
this.subscription = this.addEmployeeData().subscribe();
}
不要忘记取消订阅以避免内存泄漏:
ngOnDestroy(): void {
this.subscription.unsubscribe();
}