任务
我有3个可观察到的http1$ http2$ http3$,它们是http请求。
const 1$= this.myService.someFnReturnAnObservale({});
我有另一个可观察到的isAuth$作为我的流源。我需要从http3$那里得到回应。
上下文
为了使http3 3$,http3 2$必须首先响应某些内容。依赖于isAuth$值,如果它发射true,那么http1 2$也必须等待http1 1$来响应,如果它发出false,那么就不需要http1 1$。
我指的是成功或错误,所以我可以将一些逻辑应用于它,并决定流到下一个可观察或不可观察的地方。
编码
的逻辑的方法。
const 23$= http2$.pipe( first(),map(res => { // =>,返回布尔标志}),catchError(err => {返回( false );//如果http2 2$响应有错误,也返回false }),map(res =>{ // if响应(即上面的标志)是false // pop消息返回res;),过滤器( res => res === === true),//仅在此mergeMap之后订阅http3 3$(res => http3 3$ );
isAuth$有两个逻辑,所以:const initWithoutAuth$ =of(http1 23$);//不需要http1 1$ const initWithAuth$ = http1$.pipe(第一个(),map(res => {/ some,返回布尔标志}),catchError(err => {返回( false );//如果http1 1$响应带有错误,也返回false }),映射(res => { // if响应(这是上面的标志)为false // pop消息返回res;),过滤器( res => res === === true),//仅在此mergeMap之后订阅http23 23$(res => http23 23$ );
每当
isAuth$.pipe( switchMap(res => /))是否真的取消了curernt流(http请求),以便在另一个请求中重新启动?雷丝?.subscribe( res => { console.log(
init,res);//未达到预期结果},err => {} );
在最后一步订阅时,我期望得到observable.
发布于 2021-12-23 09:09:05
我认为错的是这条线
const initWithoutAuth$ = of(http23$);使用这一行,您基本上可以说initWithoutAuth$是一个可观察的,它通知(发射)另一个可观测的,即通知http23$。
在我看来,initWithoutAuth$应该简单地设置为http23$,而不是of(http23$)。
如果这样做,还可以将catchError从initWithAuth$和initWithoutAuth$中删除,并将其添加到最终可观察的链中,如下所示
isAuth$.pipe(
switchMap(res => // does this really cancel curernt stream (http requests) to start over within the other one?
res ? initWithAuth$ : initWithoutAuth$
),
catchError(err => {
return of(false); // in case http1$ or http2$ response with error, also return false
}),
).subscribe(
res => {
console.log(`init`, res); // not the desired result yet
},
);作为最后一个音符。我认为您在每次调用http之后使用的first操作符并不是必需的。http客户机返回一个可观察到的值,最多只通知一个值,然后完成,因此first操作符是多余的。
https://stackoverflow.com/questions/70457101
复制相似问题