我怎样才能根据结果让一个可观察的调用另一个?
How can I have an observable call another one based on the result?
情况:
我有一个 http 请求,一旦我收到它,我需要发出另一个请求。但是,我提出的第二个请求取决于第一个请求的结果。比如,我的第一个请求 returns 要么通过要么失败,如果它 returns 通过我想调用 apiPass,如果失败我想 return 一个不同的 Observable。
我知道如果我在第一个之后只有一个电话,我可以使用像 mergemap 这样的东西并写像
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(mergeMap(this.http.get<any>(this.passUrl)));
但我的情况不同 - 我想使用 resPass 来知道我是否确实应该调用传递 Api,或者我是否应该改为执行失败逻辑(也应该 return可观察的,只是一个不同的)。如果第一个调用参数通过,我如何在没有不必要订阅的情况下映射到一个 Observable (http.get(this.passUrl)
),如果参数失败则映射到另一个 Observable (otherObservable
)?
在这两种情况下,我的第一个电话应该 return http code 200
,所以这也不是 http 故障的问题。
有线索吗?
如果我理解你的问题,我会按照这些思路尝试一些事情
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(
// concatMap is the preferred operator for typical http operations, see below for more details
concatMap(({id:string, resPass:boolean}) => resPass ?
this.http.get<any>(this.passUrl) :
otherObservable)
);
在处理 http 异步请求时通常最好使用 concatMap
运算符,因为这样的运算符确保我们在继续其他可观察相关的异步操作之前收到来自 http 的响应,例如在这种情况下在第一个 returned.
之后,我们有可能进行另一个 http 调用
在 concatMap
中,我们将预期值的结构定义为 return 从使用解构的第一次调用(即使用这种形式 ({id:string, resPass:boolean})
),然后,根据值ressPass
我们要么执行第二个 http 调用,要么我们 return otherObservable
,假设这已在某处定义。
您可能会从 rxjs 与 http 的典型使用模式中得到一些启发 looking at this article。
情况:
我有一个 http 请求,一旦我收到它,我需要发出另一个请求。但是,我提出的第二个请求取决于第一个请求的结果。比如,我的第一个请求 returns 要么通过要么失败,如果它 returns 通过我想调用 apiPass,如果失败我想 return 一个不同的 Observable。
我知道如果我在第一个之后只有一个电话,我可以使用像 mergemap 这样的东西并写像
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(mergeMap(this.http.get<any>(this.passUrl)));
但我的情况不同 - 我想使用 resPass 来知道我是否确实应该调用传递 Api,或者我是否应该改为执行失败逻辑(也应该 return可观察的,只是一个不同的)。如果第一个调用参数通过,我如何在没有不必要订阅的情况下映射到一个 Observable (http.get(this.passUrl)
),如果参数失败则映射到另一个 Observable (otherObservable
)?
在这两种情况下,我的第一个电话应该 return http code 200
,所以这也不是 http 故障的问题。
有线索吗?
如果我理解你的问题,我会按照这些思路尝试一些事情
return this.http.post<{id:string, resPass:boolean}>(this.urlFirst, bodyObject)
.pipe(
// concatMap is the preferred operator for typical http operations, see below for more details
concatMap(({id:string, resPass:boolean}) => resPass ?
this.http.get<any>(this.passUrl) :
otherObservable)
);
在处理 http 异步请求时通常最好使用 concatMap
运算符,因为这样的运算符确保我们在继续其他可观察相关的异步操作之前收到来自 http 的响应,例如在这种情况下在第一个 returned.
在 concatMap
中,我们将预期值的结构定义为 return 从使用解构的第一次调用(即使用这种形式 ({id:string, resPass:boolean})
),然后,根据值ressPass
我们要么执行第二个 http 调用,要么我们 return otherObservable
,假设这已在某处定义。
您可能会从 rxjs 与 http 的典型使用模式中得到一些启发 looking at this article。