gpt4 book ai didi

javascript - Angular - 检测两个订阅何时更新

转载 作者:行者123 更新时间:2023-11-30 09:29:20 25 4
gpt4 key购买 nike

在一个组件中,在 ngOnInit() 中我有两个数据服务订阅。一旦两个订阅都返回,我想做一些处理。最好的方法是什么?我可以在每个结束时处理,这似乎有点低效,并且不适用于首先激活的订阅,

谢谢,

组件.TS

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

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

数据服务

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
}

}

最佳答案

您可以使用 Observable#forkJoin对 Observable 的作用。当所有 observables 完成时,它发出每个的最后一个值,

Observable.forkJoin(this.dataService.dataA(), this.dataService.dataB())
.subscribe(val => /* val is an array */)

关于javascript - Angular - 检测两个订阅何时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47338271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com