Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs behavior subject set value from component

Tags:

angular

rxjs

I'm trying to achieve the following:

I have a service A, this service holds an rxjs behaviorsubject:

public publishedList:BehaviorSubject<Data> = new BehaviorSubject<Data>(null)

getlist():Observable<Data> {
return this.http.post(......).map((responseData) => {
 this.publishedList.next(responseData)
 this.publishedList.asObservable().share
 }
}

Component A listens to this behaviorsubject using subscribe in the constructor.
No issues here.

Now component B comes in to place and holds a button that should be able to clear or empty the publishedList in the service and Component A should be updated.

Is this possible? How do I achieve this?

Thanks

like image 773
Maniac_1979 Avatar asked Jan 18 '17 07:01

Maniac_1979


People also ask

How do I access values in BehaviorSubject?

let value = myBehaviorSubject. getValue();

Can you subscribe to a behavior subject?

BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are: It needs an initial value as it must always return a value on subscription even if it hasn't received a next()

How do I use BehaviorSubject in RxJS?

1. First create a BehaviorSubject in order service which holds the initial state of order count ,so that it can be used by any component. 2. Now all observers(3 components) need to subscribe to source observable to get current value and show it on UI.


Video Answer


1 Answers

add this method to your service

setList(data:Data) {
  this.publishedList.next(data);
}

and call it from component B

like image 157
Günter Zöchbauer Avatar answered Oct 23 '22 20:10

Günter Zöchbauer