简体   繁体   English

Angular2 Http双重订阅

[英]Angular2 Http double subscribe

Is it possible to call Subscribe method two times?是否可以调用两次Subscribe方法?

I'm trying to build api factory, which saves data in the factory, but that data can be use by different component on each ajax call.我正在尝试构建 api 工厂,它将数据保存在工厂中,但该数据可以由每个 ajax 调用的不同组件使用。

factory工厂

export class api {

    result = [];

    constructor (protected http: Http) { }

    getData ()
    {
        return this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
    }
}

test component, which is calling subscribe method again测试组件,再次调用subscribe方法

export class TestPage {

    showListResult; 

    constructor (protected api: api) {

        this.api.getData().subscribe(res => this.showListResult = res)
    }

}

You can return new Observable wrapper.您可以返回新的 Observable 包装器。 Something like this should work:像这样的东西应该工作:

import {Observable} from 'rxjs/Observable'

export class api {

    result = [];

    constructor (protected http: Http) { }

    getData () {
        return new Observable(observer => {
            this.http.get('./friends.json')
                .map((res: Response) => res.json())
                .subscribe(res => {
                    this.result = res;
                    observer.next(res);
                    observer.complete();
                });
        });
    }
}

If you want to make the HTTP request once, and share the result to multiple subscribers, then I suggest using a connectable observer that publishes and replays the last value emitted:如果您想发出一次 HTTP 请求,并将结果共享给多个订阅者,那么我建议使用可连接的观察者来发布和重放最后发出的值:

this.observable = http.get('...').map(t=> t.json()).publishReplay().refCount();

Each new subscriber will replay the last emitted value without making a new HTTP request.每个新订阅者将重播最后发出的值,而无需发出新的 HTTP 请求。

Demo Plnkr演示计划

This answer is similar to this SO question and answer .这个答案类似于这个SO question and answer

For later versions you can use the .share() from RxJs, ( https://rxjs.dev/api/operators/share ).对于更高版本,您可以使用 RxJs 中的.share() ( https://rxjs.dev/api/operators/share )。

.publishReplay().refCount() as described by pixelbits is deprecated and replaced by .share() to be able to not call the method again but actually subscribe to the return data. pixelbits 所描述的.publishReplay().refCount()已被弃用并被.share()取代,以便能够不再调用该方法但实际订阅返回数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM