twilliams
twilliams

Reputation: 475

How to replace http observable with new observable?

I think I am fundamentally not understanding the concept of rxjs observables with angular 2.

I create an observable property that others can subscribe to and get the data for the result of an http call.

What do I do if I want to make another http request, perhaps with some modified parameters to pull back some new data? Do I just replace the observable with this new observable? Does this break the subscription my subscribing components had with the previous observable?

Upvotes: 4

Views: 2351

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

Disclaimer: I haven't used angular2 but I do use RxJS fairly frequently.

I can say that typically the case is that for single shot things like an http request the Observable generated will only ever get one result from that request. If you want to make more requests then you will need to call the method again. i.e.

From the docs

$http.get('/people.json').map(res => res.json()).subscribe(people => this.people = people);

Now if you are planning on making several subsequent requests then generally you will trigger the call with some other event, maybe a user event or network event, you could even set it up to run periodically every couple of seconds. To not "break the chain" you would need to to use one of the flatMap (which is basically .map().merge()) variants to flatten out the results into a single chain.

For instance if you had an arbitrary event (note syntax may vary a little as there are a couple versions of RxJS out there):

Rx.Observable.fromEvent($someButton, 'click')
             //Gather the parameters for the request
             .map(e => {id : 'abc123'})
             //Flatten each request into a single stream so the observer
             //never knows the difference 
             .flatMap(params => $http.get(`/people/${params.id}`), 
                      (params, res) => res.json())
             //Do your update here
             .subscribe(person => this.people[person.id] = person);

Upvotes: 4

Related Questions