首页 > 解决方案 > Angular 重新触发订阅 http 调用

问题描述

我有一个组件,我在其中获取要通过服务显示的数据。我在组件的 ngOnInit 方法中订阅服务方法(它只是将 HTTP 响应作为可观察的方式传递)。

我现在需要更新数据,并再次触发调用。(下面代码中的toggleKpi方法)

做这个的最好方式是什么?我不想在每次刷新时取消订阅和重新订阅。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { KpiService } from '../services/kpi.service';
import { Subscription } from 'rxjs';
import { Kpi } from '../models/kpi.model';

@Component({
  selector: 'app-kpi-list',
  templateUrl: './kpi-list.component.html',
  styleUrls: ['./kpi-list.component.scss']
})
export class KpiListComponent implements OnInit, OnDestroy {

  kpis: Kpi[] = [];
  deviceId: string;
  kpiSubscription: Subscription;
  displayedColumns: string[] = ['name', 'info', 'version', 'description', 'unit', 'select'];

  constructor(private route: ActivatedRoute, private kpiService: KpiService) { }

  ngOnInit() {
    this.deviceId = this.route.snapshot.parent.paramMap.get('deviceId');
    this.kpiSubscription = this.kpiService.getKpiConfiguration(this.deviceId).subscribe(res => {
      this.kpis = res.body;
    });
  }

  ngOnDestroy(): void {
    this.kpiSubscription.unsubscribe();
  }

  toggleKpi(element): void {
    // Here I need to refresh / retrigger the data
  }

}

标签: angularrxjs

解决方案


您可以使用repeatWhen运算符:


triggerer = new Subject<any>;

ngOnInit() {
    this.deviceId = this.route.snapshot.parent.paramMap.get('deviceId');
    this.kpiSubscription = this.kpiService.getKpiConfiguration(this.deviceId)
      .pipe(repeatWhen(this.triggerer))
      .subscribe(res => {
        this.kpis = res.body;
      });
  }

toggleKpi(element): void {
    // Here I need to refresh / retrigger the data
    this.triggerer.next();
  }

推荐阅读