使用Angular2重新加载Observable

时间:2017-05-20 16:25:46

标签: angular observable angular2-observables

说明

我目前正在使用Angular2(我猜是Angular4)。我正在订阅this.policyService.getBaseCommission().subscribe(response => response)中的服务constructor。此数据可以从同一页面上的表单更新。

问题:

我希望能够刷新该订阅,重新加载数据并将其显示在html中,而无需手动刷新页面。关于SO的一些答案谈到了RC中的解决方案。我在4.0。我希望能够在db中添加记录,并刷新已经订阅的数据。

问题:

如何在不重新加载页面的情况下刷新数据?如何让我的订阅触发另一个请求并相应地更新Angular2

到目前为止我尝试了什么:

虽然这确实有效,但我再次订阅并进行多次刷新,我每次都会创建新的订阅 - 至少我认为这是真的......

constructor() { this.reloadData(); }

reloadData () : void {
    this.policyService.getBaseCommission().subscribe(response => response)
}

// this gets called from the form on the page and should reload data
createPolicy () : void {
    this.policyService.anotherServiceCall().subscribe(response => {
        this.reloadData();
    });
}

1 个答案:

答案 0 :(得分:1)

据我所知,您希望在开始时调用getBaseCommission,然后在每次表单更新时调用它。您可以将表单更新建模为流:

formUpdates = new Subject<any>();
当您需要致电anotherServiceCall

时,

写入此流

this.formUpdates.next();
之后

重新加载佣金:

this.formUpdates
  .switchMap(() => {
    return this.policyService.anotherServiceCall();
  })
  .startWith('initial')
  .switchMap((x) => {
    return this.policyService.getBaseCommission(x);
  })
  .subscribe((commission) => {
    this.commission = commission;
  });

注意使用startWith需要在更新表单之前在init上加载佣金。

检查this plunker是否有工作示例。