How to embed services with Async call for constructor, Angular 2

This is the problem: I have a service that makes an HTTP request in the constructor:

constructor(public http: Http, public geolocation: Geolocation) { this.http = http; this.geolocation = geolocation; //Http request... this will set variable forecast of the class when complete. this.getForecast(16); } 

then I embed this service in a component like this:

  constructor(public connector: ApiConnector) { this.forecast = connector.forecast; } 

If I try to use the component class prediction element on the component decorator, as I here:

 @Component({ selector: 'app', directives: [MainForecast, DailyForecast], template: ` <main-forecast [main-weather]="forecast"></main-forecast> <daily-forecast [weather-list]="forecast.list"></daily-forecast> `, }) 

I get the error "I can not read the list of undefined properties in ..."

Is it possible to work with promises in the component constructor?

+5
source share
1 answer

Angular2 is recommended to do the hard work inside ngOnInit NOT inside the constructor.

ngOnInit is a lifecycle binding / event.

+1
source

Source: https://habr.com/ru/post/1239502/


All Articles