Angular6 - 从一个 http 请求到另一个 http 请求的响应值 header 作为没有嵌套订阅的选项
Angular6 - value of response header from one http request to another one as option without nested subscribes
我需要使用 http get 请求从 api 端点检索所有指定记录。 X-Total 响应 header 中提供了可用记录总数的信息。
我尝试通过一个 http 请求检索 X-Total 响应 header 的值,然后将该值作为 X-Size header 的值传递给另一个 http get 请求 - 这种方法导致在嵌套订阅中:
getTotalRecords () {
return this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': '1'
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
})
};
getData() {
this.getTotalRecords().subscribe(data => {
this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': data.headers.get('X-Total')
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
}).subscribe(data => {
console.log(data.body);
})
})
};
这行得通,但在我看来必须有更好的方法来做到这一点。此外,我将此代码直接放在一个组件中,因为我无法使用它提供服务 - 如果我必须订阅一个来创建另一个,我不知道如何 return 一个可观察的。
谢谢
您可以使用 concatMap
调用内部 Observable,然后 share
在返回 Observable 之前确保您不会在进行多个订阅时进行多次 HTTP 调用:
getData() {
return this.getTotalRecords().pipe(
concatMap(data => this.http.get(...)),
share(),
);
}
我需要使用 http get 请求从 api 端点检索所有指定记录。 X-Total 响应 header 中提供了可用记录总数的信息。 我尝试通过一个 http 请求检索 X-Total 响应 header 的值,然后将该值作为 X-Size header 的值传递给另一个 http get 请求 - 这种方法导致在嵌套订阅中:
getTotalRecords () {
return this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': '1'
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
})
};
getData() {
this.getTotalRecords().subscribe(data => {
this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': data.headers.get('X-Total')
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
}).subscribe(data => {
console.log(data.body);
})
})
};
这行得通,但在我看来必须有更好的方法来做到这一点。此外,我将此代码直接放在一个组件中,因为我无法使用它提供服务 - 如果我必须订阅一个来创建另一个,我不知道如何 return 一个可观察的。
谢谢
您可以使用 concatMap
调用内部 Observable,然后 share
在返回 Observable 之前确保您不会在进行多个订阅时进行多次 HTTP 调用:
getData() {
return this.getTotalRecords().pipe(
concatMap(data => this.http.get(...)),
share(),
);
}