簡體   English   中英

優化 api 調用 rxjs

[英]optimise api calls rxjs

我有一個數組,我想遍歷數組並調用每個項目的服務器數據。 我想在加載頁面時顯示一個微調器,因為 api 處於掛起狀態。

當前解決方案:

  getRecordings(classroom) {
    return this.sysAdminService.getMeetingRecordings(classroom.meeting_id).subscribe(res => {
      classroom.recordings = res;
    });
  }

Api 調用:

 this.classRoomsToDisplay.map((classroom) => {
      classroom.showAttendees = false;
      classroom.recordings = null;
      this.getRecordings(classroom);
    });

如上所述,我訂閱了數組中每個項目的 observable。我想知道是否有更好的方法使用 rxjs、concatMap 來做到這一點? 我不想等待整個數組的 api 調用完成,我想在該項目的 api 調用完成后立即顯示結果。

從您顯示的數據中,不清楚您使用哪個屬性來顯示數據。 我假設它是classroom.showAttendees因為它是一個布爾值。

您可以使用 RxJS forkJoin函數來組合多個 observable 並訂閱一次,而不是有多個訂閱。 您可以使用tap運算符切換數組中每個項目的showAttendees標志作為副作用。

嘗試以下

complete$ = new Subject<any>();

getRecordings(classroom): Observable<any> {   // <-- return the HTTP request observable
  return this.sysAdminService.getMeetingRecordings(classroom.meeting_id).pipe(
    tap => {
      classroom.showAttendees = true;         // <-- set the flag to show data
      classroom.recordings = res;
    }
  );
}

ngOnInit() {
  // `reqs` is an array of observables `[getRecordings(classroom), getRecordings(classroom), ...]`
  const reqs = this.classRoomsToDisplay.map((classroom) => {
    classroom.showAttendees = false;
    classroom.recordings = null;
    return this.getRecordings(classroom);
  });

  forkJoin(reqs).pipe(takeUntil(this.complete$)).subscribe();   // <-- trigger the HTTP requests
}

ngOnDestroy() {
  this.complete$.next();        // <-- close open subscriptions
}

模板

<div *ngFor="classroom of classRoomsToDisplay">
  <ng-container *ngIf="classroom.showAttendees">
    {{ classroom.recordings }}
  </ng-container>
</div>

現在,由於我們在tap運算符中分配值,因此每個項目的數據將在它們到達時立即顯示。

您應該更喜歡使用異步管道而不是訂閱。

例子:

<ul>
  <li *ngFor="let attendee of attendeesWithData">Attendee: {{ attendee.attendee }}, duplicated: {{ (attendee.duplication | async) || 'pending' }}</li>
</ul>

在這個例子中,異步操作是字符串的重復,每次請求需要更長的時間來演示。

@Injectable()
export class DuplicateService {

  times = 1;

  constructor() { }

  getDuplicated(s: string): Observable<string> {
    return timer(1000 * this.times++).pipe(
      map(() => s + s),
    );
  }
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  private attendees: string[] = ['A', 'B', 'C', 'D', 'E', 'F'];

  attendeesWithData = this.attendees.map(attendee => ({ 
    attendee,
    duplication: this.duplicateService.getDuplicated(attendee),
  }));

  constructor(private duplicateService: DuplicateService) {}
}

結果,每一秒一個列表項都將其狀態從掛起切換到重復的字符串。

另見stackblitz: https ://stackblitz.com/edit/angular-ivy-rtx6cg ? file = src/app/app.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM