Angular 7 - 嵌套 Observables [英] Angular 7 - nesting Observables
问题描述
我有一个使用参数 :client_name
的 Angular 路由,以及一个带有方法 getClientDetails(client_name)
的服务,用于从基于 的 HTTP API 获取数据:client_name
.两者都是独立工作的 Observable 方法,但是当我组合 2 个 observable 时,API 调用会在获取参数之前运行(client_name 未定义):
I have an Angular route which uses a parameter :client_name
, and a service with method getClientDetails(client_name)
to fetch data from an HTTP API based on :client_name
. Both are Observable methods working on their own, but when I combine the 2 observables then the API call runs before the params has been fetched (client_name is undefined):
this.route.params.subscribe(params => {
this.client_name = params['client_name'];
this.dataService.getClientDetails(this.client_name).subscribe(
clientdata => {
this.client = clientdata;
console.log(clientdata);
});
如何链接两个 observable 以便 API 仅在 :client_name
返回后运行?
How can I chain both observables so the API only runs once the :client_name
is returned?
推荐答案
我们可以在这个场景中使用可管道化的 RxJS 操作符.
We can make use of pipeable RxJS operators for this scenario.
首先,我们可以使用 RxJS 的 mergeMap 来映射来自route
进入内部可观察对象.如果定义了 params
和 params['client_name']
,我们将 params['client_name']
分配给 client_name
> 属性,类似于您的初始代码.然后,我们从 dataService
调用 getClientDetails()
方法.如果 params
不存在,我们将 null
转换为一个 observable,并返回它.
First, we can use RxJS's mergeMap to map over the observable values from route
into an inner observable. If params
and params['client_name']
are defined, we assign params['client_name']
to the client_name
property, which is similar to your initial code. Then, we call the getClientDetails()
method from dataService
. If the params
do not exist, we convert null
into an observable, and return it.
随后,可观察对象在 .subscribe()
块中返回.从那里,我们可以将响应分配给 client
属性.
Subsequently, the observables are returned in .subscribe()
block. From there, we can assign the response to the client
property.
import { mergeMap } from 'rxjs/operators';
import { of } from 'rxjs';
.
.
this.route.params.pipe(
mergeMap(params => {
if (params && params['client_name']) {
this.client_name = params['client_name'];
return this.dataService.getClientDetails(this.client_name);
} else {
return of(null)
}
})
).subscribe(response => {
// handle the rest
this.client = response;
})
这篇关于Angular 7 - 嵌套 Observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!