javascriptangularrxjsobservableswitchmap

How can I NOT wait for both observables to come and use data of 1 observable in swtichmap?


In this code below , I want student list to be rendered immediately and not wait for the second observable , but when second observable comes , it should check that student is not enrolled in all courses and then enable the button to add to course.

https://stackblitz.com/edit/angular-ivy-trnr9r?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2FdummyApi.ts,src%2Fapp%2Fapp.module.ts

enter image description here

enter image description here

enter image description here


Solution

  • studentDataList.pipe(switchMap(...courseDataList...))

    to

    courseDataList.pipe(switchMap(...studentDataList...))

    ts

    export class AppComponent {
      name = 'Angular ' + VERSION.major;
    
      studentDataList: Observable<IStudentData[]> = getStudentList(); // no delay
      courseDataList: Observable<ICourseData[]> = getCourseList(); // data comes after 3 seconds
    
      resultData = this.courseDataList.pipe(
        map(({length}) => length),
        // startWith(Infinity),
        switchMap((len) => this.studentDataByLength(len))
      );
    
      studentDataByLength(length: number){
        return this.studentDataList.pipe(
          map((datas) => datas.map((d) => ({...d, enable: d.courseCount < length})))
        );
      }
    
      ngOnInit() { }
    }
    

    html

    <div class="container">
      <div class="list" *ngIf="resultData | async as studentData">
        <div *ngFor="let student of studentData">
          <div>{{ student.name }}</div>
          <button class="btn" [disabled]="student.enable">Add to course</button>
        </div>
      </div>
    
      <div class="list" *ngIf="courseDataList | async as courseData">
        <div *ngFor="let course of courseData">
          <div>{{ course.name }}</div>
        </div>
      </div>
    </div>