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 fected data from service on component in angular

I am a beginner with Angular.
I have a problem with my angular service and component.
I have a component Register and a service Country.

I would like to get all countries from API to list it in my form and the country list need to be available in all other components of my app.

My service look like that :

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

```
@Injectable({
    providedIn: 'root',
})
export class CountryService {
    public country = new Array<CountryModel>();

    constructor(
        private http: HttpClient
    ) {
    }

    public getAll(): Observable<CountryModel[]> {
        console.log('getAll');
        return this.http.get<CountryModel[]>(API_URL + '/countries');
    }
}

And my component :

export class RegisterComponent implements OnInit {
    constructor(
        private countryService: CountryService
    ) {
        this.countryService = countryService;
    }

    ngOnInit() {
        console.log(this.countryService.getAll())
    }
}

I have two problems :

  1. My console log return me a Observable, but i would like to get an array of CountryModel instead, how can i do it ?
  2. As i said previously, i need to have my country list in every components of my application, should i need to set my service in every components constructor and remake a http call each time ? Or Angular provide a solution for that ?

Thank you in advance (And sorry if it looks like idiots question for you but i’m starting to work on angular few days ago)

>Solution :

You are seeing Observable in the console because that is what you are returning from the getAll method.

In order for you to get the countries list, you need to subscribe to the observable:

this.countryService.getAll().subscribe(countries => {
    console.log(countries);
});

As for your second question, you do need to inject the service into each component, but you can avoid a new HTTP request for each time the getAll method is called by storing the response the first time around and then returning that for subsequent calls to that method.

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