Home > other >  How to get fected data from service on component in angular
How to get fected data from service on component in angular

Time:02-05

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 :

```
@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)

CodePudding user response:

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.

  •  Tags:  
  • Related