Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get data from BehaviourSubject in Angular?

I want to access to the locationRoot properties.
How can I do it?

[Service Code]

getCityByLocationRootName(locationRoot: LocationRoot) {
    const behaviourSubjectCity = new BehaviorSubject<City>(this.city);
    const url = this.API_GEOCODE + locationRoot.name + '&appid=' + this.API_KEY;
    this.httpClient
      .get<City>(url).subscribe({
        next: city => behaviourSubjectCity.next(city),
        error: error => console.error(error)
      });
    return behaviourSubjectCity;
  }

[Component Code]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

getLocationRootByName() {
    const locationRoot = this.dataService.getCityByLocationRootName(this.locationRoot);
  }

>Solution :

You don’t need to use subject, when you can do

return this.httpClient.get<City>(url)

And after subscribe it into your component.

getLocationRootByName() {
    let locationRoot;
    this.dataService.getCityByLocationRootName(this.locationRoot).subscribe({
        next: city => locationRoot = city,
        error: error => console.error(error)
      });
}

If you want to handle error in your service, so you can use pipe to do that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading