Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
I have some question about rxjs function. Actually, I make a request to http server. The way I receive data from http server is two steps because each request returns only 10 items, not entire items. Each request has page number so, if I have a total number of 100 items, I have to make quest 10 times. So, before making request one by one, I extract the total number of pages first, then I loop through request as many as the number of pages. In order to do it, I use switchMap function like below.
getItems(id: string) {
return this.dataService.getPageNum(id).switchMap (
(page_num: number) => {
for(let i=1; i<=page_num; i++) {
this.dataService.getItems(id, i).subscribe(
(data: Object) => {
this.items.push(data);
It returns error error TS2345: Argument of type '(page_num: number) => void' is not assignable to parameter of type '(value: number, index: number) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.
So, I searched some information regarding this issue, I found something,
Angular 2 - RxJS Switch Map Issue
but I do not understand what question and answer says well. That means I should put Observable.empty() to make it work? Also, I even tried to return Observable.of(null) and Observable.empty(), it says that Property 'empty' does not exist on type 'typeof Observable' even I imported that function.
You are returning nothing inside of switchMap function. It expects from you do to so (return an observable), that is the purpose of mergeMap, switchMap and concatMap, to flat a map. Check this site, I hope it can help you to get started.
You have to manage the subscription from the flated map not inside of the switchMap function. So this line is not correct:
this.dataService.getItems(id, i).subscribe(
your.component.ts
getItems(id: string) {
return this.dataService.getPageNum(id)
.switchMap((page_num: number) => {
for(let i=1; i<=page_num; i++) {
return this.dataService.getItems(id, i);
}).subscribe((data: Object) => {
this.items.push(data);
getItems(id: string) {
return this.dataService.getPageNum(id)
.pipe(switchMap((page_num: number) => {
for(let i=1; i<=page_num; i++) {
return this.dataService.getItems(id, i);
})).subscribe((data: Object) => {
this.items.push(data);
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.