angular - 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
}
}
解决方案
您可以使用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();
}
推荐阅读
- python - 如何在熊猫数据框中获得 CatBoost 的特征重要性?
- mysql - 从链接到数据库的组合框中删除 id 时出错
- python-3.x - 未找到气流 task_id
- asynchronous - 如何通过 clojure 的 core.async 中的通道进行通信?
- r - 如何编写 R 代码以通过特定单元格直接从 excel 中读取?
- java - 表格行字符替换为“?” mvn包后
- mysql - 有两个 MySQL 表,获取第一个表键的每个值的最后一个结果
- java - java stars程序中的逻辑是什么?
- node.js - Bittrex api V3 新订单(未经授权)
- typescript - 映射类型时省略只读属性