【问题标题】:Angular retrigger subscription to http callAngular 重新触发订阅 http 调用
【发布时间】: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 方法进行一些更改,您就无法“刷新”同一个订阅。

标签: angular rxjs


【解决方案1】:

你可以使用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();
  }

【讨论】:

    【解决方案2】:

    您可以创建一个可重用的方法来获取它。

    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();
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2019-09-22
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多