我Observable
对服务器有两个请求:
this.initService.__init__(res).subscribe((profile) => {
console.log(profile); // It works
this.initService.initializePeriod(profile).subscribe((period) => {
console.log(period); // It does not work
});
});
当第一次得到响应时,它会调用第二次,但我无法获得第二次订阅的结果。我知道,在这种情况下最好使用 Promises,但我需要将结果从第一个请求传递到第二个请求,承诺不允许这样做。
我尝试使用它,但警报消息不起作用:
this.initService.__init__(res)
.pipe(
mergeMap(profile => this.initService.initializePeriod(profile)))
.subscribe((response) => {
alert('aa');
});
也试过这个:
this.initService.__init__(res)
.mergeMap(profile => this.initService.initializePeriod(profile))
.subscribe((response) => {
alert('aa');
});
您可以使用switchMap
rxjs 运算符来链接可观察对象。
import { switchMap } from 'rxjs/operators';
this.initService.__init__(res)
.pipe(
switchMap(profile=> this.initService.initializePeriod(profile))
).subscribe((period) => {
console.log(period);
});
如果你想得到两者的回应,那么使用 mergeMap
import { mergeMap } from 'rxjs/operators';
this.initService.__init__(res)
.pipe(
mergeMap(
profile=> this.initService.initializePeriod(profile),
(profile, period) => {
return [profile,period];
}
)
).subscribe((response) => {
console.log(response[0]); //profile
console.log(response[1]); //period
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句