加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何取消订阅forkJoin返回的Observable?

发布时间:2020-12-17 07:20:00 所属栏目:安全 来源:网络整理
导读:在我的Angular2-typescript应用程序中,我只使用forkJoin在所有并行HTTP调用完成后返回一个Observable. 问题:订阅回调一直无限期地执行 这是我的代码: http.service import {Http} from "@angular/http";constructor (private _http: HTTP) {}makeGetReques
在我的Angular2-typescript应用程序中,我只使用forkJoin在所有并行HTTP调用完成后返回一个Observable.

问题:订阅回调一直无限期地执行

这是我的代码:

http.service

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

constructor (private _http: HTTP) {}

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

my.service

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

my.component

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

我尝试了什么(同样的问题):

>在Http.service而不是Promise中返回一个Observable
>在my.component中使用.first().subscribe()而不是subscribe()
>把this.mySub.unsubscribe();在ngOnInit的末尾而不是在subscribe回调中(也使用setTimeout(()=> ….))

正如 forkJoin reference所说,它

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

这意味着运算符从已完成的observable中获取值,并返回具有单个值的已完成的observable.没有必要取消订阅.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读