Charlie
Charlie

Reputation: 1766

Trigger observable manually?

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.

Upvotes: 3

Views: 4586

Answers (1)

yurzui
yurzui

Reputation: 214275

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

Upvotes: 2

Related Questions