问题描述
我有一个订阅中的订阅,并且我想链接它,但是我不确定应该如何继续,因为if块内部已订阅了实习生。
authenticationService.isLoggedIn$.subscribe(isLoggedIn => {
this.isLoggedIn = isLoggedIn;
if (isLoggedIn) {
socketService.initSocket();
authenticationService.refresh().subscribe(time => {
this.timeOut = time.expirationTime;
this.setTimeout(this.timeOut);
});
} else {
clearTimeout(this.userActivity);
socketService.destroySocket();
}
});
我希望以某种方式链接它,使其只能订阅一次。 我当时认为将它放在某个可以顺序运行的数组中会很好吗?
解决方法
switchMap
可以解决问题。沿着这些路线……
return authenticationService.isLoggedIn$.pipe(
tap(isLoggedIn => this.isLoggedIn = isLoggedIn),switchMap(isLoggedIn => isLoggedIn ? authenticationService.refresh() : of(null)))
.subscribe(time => {
if (time) {
this.timeOut = time.expirationTime;
this.setTimeout(this.timeOut);
} else {
clearTimeout(this.userActivity);
socketService.destroySocket();
}
});
,
您可以使用iif运算符:
let subscribeToFirst;
const firstOrSecond = iif(
() => subscribeToFirst,of('first'),of('second'),);
subscribeToFirst = true;
firstOrSecond.subscribe(value => console.log(value));
如果您有两个以上的选项,则可以在switchMap中手动使用if语句。
myObs$
.pipe(
switchMap(val => {
if(a) { return obsA$ }
else if(b) { return obsB$ }
else { return obsElse$ }
})
).subscribe();