我有一个组件,用于在其中获取要通过服务显示的数据。我正在订阅该组件的ngOnInit方法中的service方法(它只是将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
}
}
答案 0 :(得分:2)
您可以使用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 :(得分:1)
您可以制作一个可重用的方法来获取它。
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();
}
}