如何在动态数组中设置订阅

数字污染

我正处于学习 Angular 的早期阶段,正在尝试了解 RxJS、Observable 等。可能我在语法和概念上都有问题。

所以这里我有一个服务incidentService,它获取一系列事件并将它们显示在页面上。如果该incident.requirementMet属性是,true那么我希望该incident.resolved属性在列表中每个事件的计时器上更新。导航到另一个视图时,我想取消所有订阅。

这是我迄今为止尝试过的。setIncidentSubscriptons()postIncident()方法周围出现问题

Angular v8.2 rxjs v6.4

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, Observable, timer } from 'rxjs';
import { IncidentService } from '../services/incident.service';
import { Incident } from '../models/incident';

@Component({
  selector: 'app-incident',
  templateUrl: './incident.component.html',
  styleUrls: ['./incident.component.scss']
})
export class IncidentComponent implements OnInit, OnDestroy {
  private incidentSubscriptions: Subscription[] = [];
  incidents: Incident[];

  constructor(private incidentService: IncidentService) { }

  ngOnInit() {
    this.getIncidents();
  }

  ngOnDestroy() {
    this.incidentSubscriptions.forEach(subscription => subscription.unsubscribe());
  }

  getIncidents(): void {
    this.incidentService.getIncidents()
      .subscribe((incidents) => {
        this.incidents = incidents;
        this.setIncidentSubscriptons();
      });
  }

  setIncidentSubscriptons(): void {
    let timerDelay = 1000;

    for (const i in this.incidents) {
      if (this.incidents[i].requirementMet) {
        timerDelay += 2000;

        this.incidentSubscriptions.push(
          timer(1)
          .subscribe(
            () => { this.postIncident(this.incidents[i], timerDelay); }
          )
        );
      }
    }
  }

  postIncident(incident: Incident, timerDelay: number) {
    if (incident.resolved < 100) {
      setTimeout(() => {

        incident.resolved += 1;
        this.incidentService.updateIncident(incident).subscribe(() => {
          this.postIncident(incident, timerDelay);
        });

      }, timerDelay);
    }
  }

}
弗里多

你应该尝试用 RxJS 操作符来完成你所有的逻辑,并构建一个 Observable 来完成你所有的任务。只订阅一次最终的 Observable。

我假设this.incidentService.updateIncident(incident)只发出一次然后完成并且不使用发出的值。

import { timer, forkJoin, Observable, Subject } from 'rxjs';
import { tap, concatMap, switchMap, takeUntil, take } from 'rxjs/operators';

private onDestroy$ = new Subject();

ngOnInit() {
  this.getAndUpdateIncidents().subscribe();
}

ngOnDestroy() {
  this.onDestroy$.next();
  this.onDestroy$.complete();
}

getAndUpdateIncidents(): Observable<any[]> { // 'any' is whatever this.incidentService.updateIncident(incident) returns
  return this.incidentService.getIncidents().pipe(
    tap(incidents => this.incidents = incidents), // assign the returned incidents
    switchMap(incidents => this.updateIncidents(incidents)), // switch to an Observable that updates the incidents
    takeUntil(this.onDestroy$) // unsubscribe on destroy
  )
}

updateIncidents(incidents: Incident[]): Observable<any[]> {
  let timerDelay = 1000;
  return forkJoin(incidents // use forkJoin to execute an array of Observables parallely
    .filter(incident => incident.requirementMet) // only take incidents who meet the requirement
    .map(incident => { // map to an Observable that periodically updates the incident
      timerDelay += 2000;
      timer(0, timerDelay).pipe( // timer will emit numbers with a given delay
        take(100), // only take 100 numbers
        concatMap(_ => { // map to the Observable that updates the incident, 
          // concatMap ensures that the next update will only be executed when the previous completed
          incident.resolved += 1;
          return this.incidentService.updateIncident(incident);
        })
      )
    }));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类常见问题

如何在* ngFor中设置动态ID?

来自分类Dev

如何在WordPress中设置动态的“ home”和“ siteurl”?

来自分类Dev

如何在Codeigniter的会话中设置数组?

来自分类Dev

如何在动态SQL查询中设置表名?

来自分类Dev

如何在JTable中动态设置RowHeight

来自分类Dev

如何在Twig中设置多维数组?

来自分类Dev

如何在Go中设置动态结构字段?

来自分类Dev

如何在php中动态创建数组?

来自分类Dev

如何在C或C ++中创建动态堆栈的动态数组

来自分类Dev

如何在C中实现动态数组?

来自分类Dev

如何在翻新(Android)中动态设置标题

来自分类Dev

如何在pluoplad-angular-directive中设置动态url?

来自分类Dev

如何在C中的过程中创建动态数组?

来自分类Dev

如何在puppet enterprise 3.7中设置条件订阅?

来自分类Dev

如何在createSwitchNavigator中设置动态initialRouteName?

来自分类Dev

如何在React中以动态形式在状态数组中设置对象

来自分类Dev

如何在空手道中为JSON数组设置动态值

来自分类Dev

如何在Excel中混合动态数组和常量数组

来自分类Dev

如何在函数中缩短数组?(动态数组,内存泄漏)

来自分类Dev

如何在数组索引的数组中设置值

来自分类Dev

如何在整数数组中动态设置图像ID

来自分类Dev

如何在结构中设置动态键名?

来自分类Dev

如何在数组中循环数组(动态导航)

来自分类Dev

Plone-如何在事件订阅者中设置DefaultPage?

来自分类Dev

如何在java中动态填充jsonArray中的数组

来自分类Dev

如何在 OpenCL 中创建动态数组?

来自分类Dev

你如何在 Angular 2 中订阅 FormData 对象的数组?

来自分类Dev

在反应中,我如何在 ExpansionPanel 中动态设置 defaultExpanded

来自分类Dev

如何在 Angular 中设置数组形式?

Related 相关文章

  1. 1

    如何在* ngFor中设置动态ID?

  2. 2

    如何在WordPress中设置动态的“ home”和“ siteurl”?

  3. 3

    如何在Codeigniter的会话中设置数组?

  4. 4

    如何在动态SQL查询中设置表名?

  5. 5

    如何在JTable中动态设置RowHeight

  6. 6

    如何在Twig中设置多维数组?

  7. 7

    如何在Go中设置动态结构字段?

  8. 8

    如何在php中动态创建数组?

  9. 9

    如何在C或C ++中创建动态堆栈的动态数组

  10. 10

    如何在C中实现动态数组?

  11. 11

    如何在翻新(Android)中动态设置标题

  12. 12

    如何在pluoplad-angular-directive中设置动态url?

  13. 13

    如何在C中的过程中创建动态数组?

  14. 14

    如何在puppet enterprise 3.7中设置条件订阅?

  15. 15

    如何在createSwitchNavigator中设置动态initialRouteName?

  16. 16

    如何在React中以动态形式在状态数组中设置对象

  17. 17

    如何在空手道中为JSON数组设置动态值

  18. 18

    如何在Excel中混合动态数组和常量数组

  19. 19

    如何在函数中缩短数组?(动态数组,内存泄漏)

  20. 20

    如何在数组索引的数组中设置值

  21. 21

    如何在整数数组中动态设置图像ID

  22. 22

    如何在结构中设置动态键名?

  23. 23

    如何在数组中循环数组(动态导航)

  24. 24

    Plone-如何在事件订阅者中设置DefaultPage?

  25. 25

    如何在java中动态填充jsonArray中的数组

  26. 26

    如何在 OpenCL 中创建动态数组?

  27. 27

    你如何在 Angular 2 中订阅 FormData 对象的数组?

  28. 28

    在反应中,我如何在 ExpansionPanel 中动态设置 defaultExpanded

  29. 29

    如何在 Angular 中设置数组形式?

热门标签

归档