Initial value of BehaviorSubject in a service getted from HTTP API

Viewed 159

in a service I have this BehaviorSubject, and I try to get the default value using a get HTTP request:

defaultItems!: ColumnsToFilterWithItems[];
columnsToFilterWithItemsBehaviorSubject: BehaviorSubject<ColumnsToFilterWithItems[]> = new BehaviorSubject<ColumnsToFilterWithItems[]>(this.defaultItems);
constructor() {
    this.getColumnsToFilterWithItems().subscribe(columnsToFilterWithItems => {
      this.defaultItems = columnsToFilterWithItems  }) // get default data by calling a get http method
  }

In the component when I subscribe to the behavior subject (after using asObservable() method) in the ngOnInit method i can't get the default data and I have this error:

ERROR TypeError: Cannot read properties of undefined
at SafeSubscriber._next

When I hard code the default value (defaultItems), it works well. When I can call the getColumnsToFilterWithItems method to avoid this error? Thank you.

1 Answers

You're subscribing to the behaviour subject wrongly.

Try like this

this.getColumnsToFilterWithItems.subscribe(columnsToFilterWithItems => {
  this.defaultItems = columnsToFilterWithItems  
}) // get default data by calling a get http method

Incase if you're trying to get data from API use like this

getColumnsToFilterWithItems(){
  return "https://swapi.dev/api/people/1/"
}
Related