【发布时间】:2020-10-08 15:30:10
【问题描述】:
我有一个组件,我在其中获取要通过服务显示的数据。我在组件的 ngOnInit 方法中订阅服务方法(它只是将 HTTP 响应作为 observable 传递)。
我现在需要更新数据,并再次触发调用。 (下面代码中的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
}
}
【问题讨论】:
-
http完成。您不需要手动取消订阅(尽管如果用户在 http 调用完成之前离开页面,这将阻止订阅者运行)。而且由于它已经完成,如果不对您的KipService#getKpiConfiguration方法进行一些更改,您就无法“刷新”同一个订阅。