0
votes

I have a problem with Subject

this.subjectService.createNext(this.service.getData(pageNumber=1)
this.subjectService.createNext(this.service.getData(pageNumber=2)
this.subjectService.createNext(this.service.getData(pageNumber=3)

I call 3 next methods because I have to download three API pages with data (3x10).

In another component I subscribe this subject:

this.subjectService.getData()
  .pipe(flatMap(res => res))
  .subscribe((result) => {
  console.log(result);
});

I'm using flatMap because without flatMap i receive:

>> Observable {_isScalar: false, source: Observable, operator: MapOperator}
>> Observable {_isScalar: false, source: Observable, operator: MapOperator}
>> Observable {_isScalar: false, source: Observable, operator: MapOperator}

The problem is that when I'm using flatMap then I can't iterate all pageNumbers.

this.subjectService.getData()
.pipe(tap(() =>
console.log(pageNumber))) /* It returns 1,2,3

.pipe(flatMap(res => res))

.pipe(tap(() =>
console.log(pageNumber))) /* after flatMap: It returns 3,3,3

.subscribe((result) => {
console.log(result);
      });

Maybe you know how to mix flatMap (to get normal data, avoid _isScalar...) and iterate all pageNumbers per observable, not only last called with createNext(pageNumber=3).

1
What is createNext? - MikeOne
createNext is the function placed in subject.service.ts . This function includes code: this.subject.next(apiCall, pageNumber); - Bartosz Projects
This looks more complicated then it should be. Why not just use a combineLatest with 3 http calls? Or a merge? Or forkJoin? Why the additional Subject. - MikeOne

1 Answers

0
votes

You should attach your page number with the observable you created from this.service.getData.

Like this

this.subjectService
  .createNext(
    this.service.getData(1)
      .pipe(map(data => ({ data, pageNumber: 1 }))
  )

this.subjectService
  .createNext(
    this.service.getData(2)
      .pipe(map(data => ({ data, pageNumber: 2 }))
  )

this.subjectService
  .createNext(
    this.service.getData(3)
      .pipe(map(data => ({ data, pageNumber: 3 }))
  )

The data you receive with the flatmap will be

// { data: { some: 'object' }, pageNumber: 1 }
// { data: { some: 'object' }, pageNumber: 2 }
// { data: { some: 'object' }, pageNumber: 3 }