3

是否可以Subscribe两次调用方法?

我正在尝试构建 api 工厂,它将数据保存在工厂中,但该数据可以由每个 ajax 调用的不同组件使用。

工厂

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

测试组件,subscribe再次调用方法

export class TestPage {

    showListResult; 

    constructor (protected api: api) {

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

}
4

2 回答 2

3

您可以返回新的 Observable 包装器。像这样的东西应该工作:

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();
                });
        });
    }
}
于 2016-02-14T21:45:38.477 回答
3

如果您想发出一次 HTTP 请求,并将结果共享给多个订阅者,那么我建议使用可连接的观察者来发布和重放最后发出的值:

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

每个新订阅者将重播最后发出的值,而无需发出新的 HTTP 请求。

演示计划

这个答案类似于这个SO question and answer

于 2016-02-15T00:12:07.887 回答