Angular повторная подписка на http-звонок - PullRequest
1 голос
/ 18 июня 2020

У меня есть компонент, в котором я получаю данные для отображения через службу. Я подписываюсь на сервисный метод (он просто передает HTTP-ответ как наблюдаемый) в методе ngOnInit компонента.

Теперь мне нужно обновить данные и снова запустить вызов. (метод toggleKpi в приведенном ниже коде)

Как лучше всего это сделать? Я не хочу отказываться от подписки и повторно подписываться на каждую ссылку sh.

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
  }

}

Ответы [ 2 ]

2 голосов
/ 18 июня 2020

Вы можете использовать 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();
  }
1 голос
/ 18 июня 2020

Вы можете просто создать многоразовый метод для его получения.

export class KpiListComponent implements OnInit, OnDestroy {

  kpis: Kpi[] = [];
  deviceId: string;
  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.getKpi();
  }

  ngOnDestroy(): void {

  }

   getKpi() {
      this.kpiService.getKpiConfiguration(this.deviceId).subscribe(res => {
      this.kpis = res.body;
    });
   }

  toggleKpi(element): void {
     this.getKpi();
  }

}
...