franco
franco

Reputation: 697

Get updated value of an HTTP Observable

Say I have a code that gets the users from the API:

getUsers() {
   this.users$ = this.userService.getUsers();
}

And I display the users in my view using the async pipe.

At some point on my code, I'd like to call getUsers() again to fetch an updated list of users, but the view doesn't get updated with a new list because presumably its the async pipe that handles the observable and it doesn't know to call the service again.

How can I work around this issue? Do I need to use .subscribe() instead?

Upvotes: 0

Views: 70

Answers (1)

Timothy
Timothy

Reputation: 3593

This is because this.users$ observable is already completed (promise resolved by async) Simply return getUsers observable from this method and use subscribe method to fetch them

getUsers(): Observable<User[]> {
   return this.userService.getUsers();
}

Note: subscribe method doesn't mean it will listen to changes of observable, it will listen to them only if observable not completed, but as long as HttpClient completes it, you don't need to worry about memory leak

To comply it with your implementation it will be something like:

this.someService.doSomething().pipe(
  switchMap(something => this.userService.getUsers())
).subscribe(users => {})

Upvotes: 1

Related Questions