how to use behaviorsubject in angular

This post explores concrete examples of how to use behaviorSubject in angular and use as BehaviorSubject state management

what is behaviorsubject

BehaviorSubject is a type of subject that has the concept of ​​its current value in storing and emitting to all new subscribers. The current value is either the latest of the emitted value or the initial/default value if not affected. Since the current value should be present, BehaviorSubject requires the first value at the beginning.

In angular, it is a best practice to use behavoirSubject in a service. Using it in components will result in inconsistent data management since a component has a state that can be initialized, destroyed but services remain.

behaviorsubject declaration and how to use behaviorsubject in angular

/* declation in a service*/
export class MyServiceClass {
private listOfBooks = new BehaviorSubject <any []>([])     // declaration as an array
private myProfile = new BehaviorSubject <any>(null)      // declaration as an array
}

behaviorsubject set value

export class MyServiceClass {
private listOfBooks = new BehaviorSubject <any []>([])     // declaration as an array
private myProfile = new BehaviorSubject <any>(null)      // declaration as an array


constructor(private httpClient: HttpClient){
}

setListOfBooks(books : any[]){
this.listOfBooks.next(books);      // at this stage in emit the current list of books to all subscribers .
}

getListOfBooks(): BehavoirSubject<any []>{
return this.listOfBooks;      // at this stage it emit the current value to new subscribers
}


getBooksFromRemote(){
this.httpClient.get('https://remote-url-for-books').subscribe(data => {
this.setListOfBooks(data.book);   // at this state we are calling the remote api, fetch the book list and pass the list to our behavour subject.
});
}


}

behaviorsubject get value

Getting the value, you should definitely subscribe to the behavior subject in a component

/* Your code... */
export class userComponent inplement Oninit{ bookList : any; constructor(private myServiceClass: MyServiceClass){ } ngOninit(){ this.myServiceClass.getListOfBooks().subscribe( books => { this.bookList = books }) } }

 

Once you subscribe to the behavior service get method, it emits the current value if the API fetches new data. You can visit the RXJS platform to see more examples here.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *