Angular-检测两个订阅已更新的时间 [英] Angular - detecting when two subscriptions have updated

查看:58
本文介绍了Angular-检测两个订阅已更新的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个组件中,在ngOnInit()中,我有两个数据服务订阅.一旦两个订阅都返回,我想做一些处理.最好的方法是什么?我可以在每个文件的末尾进行处理,这似乎效率不高,并且无法在订阅首先激活的情况下起作用,

In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

谢谢

Component.TS

Component.TS

ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) => 
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) => 
 {
   this.dataB= dataBJSON
 }

DataService

DataService

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}

推荐答案

使用的方法取决于您希望如何接收数据:

The method used depends on how you want to receive the data:

您可以使用 zip 函数.全部发射一次后发射一次.因此与 Promise.all 相似,除了未完成时.

You can use the zip function. Emits once when all have emitted once. So similar to Promise.all except not on completion.

Observable.zip(obs1, obs2).subscribe((val) => { ... });

您可以使用 forkJoin 功能.全部完成后发出一次.就像 Promise.all .

You can use the forkJoin function. Emits once when all have completed. So exactly like Promise.all.

Observable.forkJoin(obs1, obs2).subscribe((val) => { ... });

您可以使用合并函数.按发射顺序发射,因此可能是第1个然后第2个或第2个然后第1个:

You can use the merge function. Emits in order of emission so could be 1st then 2nd or 2nd then 1st:

obs1.merge(obs2).subscribe((val) => { ... });

您可以使用 concat 函数.不管第2个是否先发射,按第1个然后第2个顺序发射:

You can use concat function. Emits in order 1st then 2nd regardless if 2nd emits first:

obs1.concat(obs2).subscribe((val) => { ... });

为了清楚起见,最好将它们分成几行.

It's best practice to split these up into a couple lines for clarity.

const obs1 = Rx.Observable.of(1,2,3);
const obs2 = Rx.Observable.of(1,2,3);
const example = Observable.zip(obs1, obs2);
//const example = Observable.forkJoin(obs1, obs2);
//const example = obs1.merge(obs2);
//const example = obs1.concat(obs2);
example.subscribe(val => { ... });

这篇关于Angular-检测两个订阅已更新的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆