typescriptangularangular2-http

Angular2 Http double subscribe


Is it possible to call Subscribe method two times?

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.

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

export class TestPage {

    showListResult; 

    constructor (protected api: api) {

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

}

Solution

  • You can return new Observable wrapper. 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();
                    });
            });
        }
    }