3
votes

I have a service with a collection of CRUD actions. One of them is a "get all" kind of deal. All return HTTP observables like:

  getUsers(): Observable<User[]> {
    return this.http.get(this.baseURL + '/api/users').map((response: Response) => response.json()).share();
  }

Now, I have one component subscribed to the service with an async pipe:

this.users = this.userService.getUsers();

<md-list-item *ngFor="let user of users | async;>

And in another component, I'd like to call the getUsers method (since it performed some actions on the data), and have the other component automatically update.

this.service.getUsers() doesn't work of course because it needs to be subscribed to.

Is there someway to make a subscription/observable permanent? Am I missing something?

I've usually done something where components subscribe to a subject in a service directly and I manually update it. But was wondering if there's some fancy shamncy way.

1
Component one does subscribe to it. Would the component react if another component does this.service.getAll().subscribe()? - Charlie
@yurzui, that was it! I can't mark your comment as the answer. :) - Charlie

1 Answers

2
votes

In the case of an observable created from an HTTP call, the corresponding request will be called twice if subscribed twice) By default such observables are cold (they can't be shared).

You can make your observable hot using the share method:

import 'rxjs/add/operator/share';

this.users$ = this.userService.getUsers().share();