如何退订forkJoin返回的Observable? [英] How to unsubscribe from an Observable returned by forkJoin?

查看:146
本文介绍了如何退订forkJoin返回的Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Angular2-typescript应用程序中,我仅在进行所有并行HTTP调用后才使用forkJoin返回一个Observable.

In my Angular2-typescript app, I'm using forkJoin to return an Observable only once all the parallel HTTP calls were made.

问题:订阅回调将无限期执行

Issue: the subscription callback keeps being executed indefinitely

这是我的代码:

http.service

import {Http} from "@angular/http";

constructor (private _http: HTTP) {}

makeGetRequest(....) {
    return this._http.get(URL)
           .map (res => res.json)
           .toPromise();

我的服务

import {Observable} from "rxjs/Observable";
import {HttpService} from "http.service"

constructor (private _httpService: HttpService) {}

myMethod(): Observable<any[]> {
 return Observable.forkJoin(
            this._httpService.makeGetRequest(
                URL1
            ),
            this._httpService.makeGetRequest(
                URL2
            )
        )
}

我的组件

import MyService from "my.service";
import Subscription from "rxjs";

constructor (private _service: MyService) {}

mySub: Subscription;

ngOnInit() {
    this.mySub = this._service.myMethod.subscribe(data => {
         data.forEach(console.log(data));
         this.mySub.unsubscribe();
     }
}

我尝试过的(相同问题):

What I tried (same issue):

  • 在Http.service中返回一个Observable而不是Promise
  • 在my.component中使用.first().subscribe()而不是仅subscription()
  • 放入this.mySub.unsubscribe();在ngOnInit的末尾而不是在订阅回调内部(也使用setTimeout(()=> ....))

推荐答案

并行运行所有可观察的序列,并收集它们的最后一个元素.

Runs all observable sequences in parallel and collect their last elements.

这意味着操作员从已完成的可观测值中获取值,并返回具有单个值的已完成的可观测值.无需取消订阅.

This means that the operator gets values from completed observables and returns a completed observable with single value. There's no need to unsubscribe from it.

这篇关于如何退订forkJoin返回的Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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