I need to be able to execute 3 observables one after another so that I can use result value from 1st one in second and also 1st and 2nd result in the third one.
Something like this (it doesn't work as the serviceId is not visible in the third request):
private setupStuff(): void {
this.initRouteParams().pipe(
switchMap(serviceId => this.getFileInfo(serviceId)),
switchMap(fileName => this.getExistingFile(serviceId, fileName)
.subscribe(response => {
console.log(response);
}))
);
}
I need to be able to execute 3 observables one after another so that I can use result value from 1st one in second and also 1st and 2nd result in the third one.
Something like this (it doesn't work as the serviceId is not visible in the third request):
private setupStuff(): void {
this.initRouteParams().pipe(
switchMap(serviceId => this.getFileInfo(serviceId)),
switchMap(fileName => this.getExistingFile(serviceId, fileName)
.subscribe(response => {
console.log(response);
}))
);
}
Share
Improve this question
edited Jul 30, 2018 at 20:29
msanford
12.2k13 gold badges71 silver badges98 bronze badges
asked Jul 30, 2018 at 20:04
Deniss M.Deniss M.
4,06020 gold badges59 silver badges112 bronze badges
3
-
Where do
serviceId
andfileName
e from? – msanford Commented Jul 30, 2018 at 20:27 -
1
serviceId
es frominitRouteParams().pipe
andfileName
fromthis.getFileInfo(serviceId)
– Deniss M. Commented Jul 30, 2018 at 20:30 - serviceId is not accessible in the third request because the scope of serviceId is limited to the first switchMap only and also piler won't find it in lexical scope – Aman Kumar Gupta Commented Jan 27, 2023 at 13:49
2 Answers
Reset to default 15You can explicitly return the value of the serviceN to the serviceN+1. Here's the idea :
private setupStuff() {
this.initRouteParams()
.pipe(
switchMap(serviceId => {
return zip(of(serviceId), this.getFileInfo(serviceId))
}),
switchMap(([serviceId, filename]) => {
return zip(of(serviceId), of(filename), this.getExistingFile(serviceId, filename))
})
)
.subscribe(([serviceId, filename, response]) => {
console.log(serviceId, filename, response);
})
}
Edit:
You can fix types errors by explicitly declare types of each input. You probably want to assign the appropriate type for response
.
managed to solve it like this:
private checkFilePresence(): void {
const first$: Observable<string> = this.initRouteParams();
const second$: Observable<string> = first$.pipe(
switchMap(config => {
return this.getFileInfo(config);
})
);
const third$: Observable<CkitExistingFileResponse> = bineLatest(first$, second$).pipe(
switchMap(([config, second]) => {
return this.getExistingFile(config, second);
})
);
bineLatest(first$, third$)
.subscribe(() => {
});
}