angular - 使一种方法依赖于另一种方法的成功运行
问题描述
我有一种情况,我需要一个服务来设置一些字段,然后才能执行 HTTP 调用。这些字段来自另一个 HTTP 调用,所以我不能异步运行它们——没有这些数据,第二个调用将失败。我想我有办法做到这一点,但我错过了一些东西——第一个方法 ( getSystemConfiguration()
) 根本没有触发,即使在链的末端肯定有一个subscribe()
调用。
我对 RxJs 有点陌生,所以我觉得这应该很简单,但我错过了什么?
// Method that gets system configuration
setApiInformation(): Observable<void> {
if (!this.apiKey || !this.checkUrl) {
return this.systemConfigurationService.getSystemConfiguration()
.pipe(
map(config => {
// None of this ever executes
this.apiKey = config.apiKey;
this.checkUrl = config.objectExistsUrl;
}));
} else {
return of();
}
}
// Method I'm trying to run
checkServerData(data: RequestParameters): Observable<ServerResponseData> {
return this.setApiInformation()
.pipe(map(() => {
let httpOptions = { headers: new HttpHeaders({ "serverApiKey" : this.apiKey }) };
return this.httpClient.put<ServerResponseData>(this.checkUrl, request, this.httpOptions);
}));
}
// Ultimate caller
let params: RequestParameters = { tenantId: 1, requestorId: 1 };
this.service.checkServerData(params)
.subscribe((response: ServerResponseData) => { this.dataExists = response.success; });
解决方案
很少有rxjs
运营商可以帮助您解决这个问题。我个人更喜欢switchMap
。这就是我将如何实现它:
this.setApiInformation().pipe(switchMap(data => {
// do something here if needed
return this.checkServerData();
})).subscribe( data => {
// do something
});