Angular 7-嵌套Observables [英] Angular 7 - nesting Observables
问题描述
我有一个使用参数:client_name
的Angular路由,以及一个使用方法getClientDetails(client_name)
的服务从基于:client_name
的HTTP API获取数据.两者都是可观察的方法,它们各自工作,但是当我结合使用这两个可观察的方法时,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);
});
如何链接两个可观察对象,以便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
转换为可观察对象,然后将其返回.
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屋!