I've been diving into Angular 2 and finding myself puzzled by the constructor. Let's take a look at the following code snippet:
import { Component, OnInit } from '@angular/core';
import { FormGroup,FormsModule,FormControl } from '@angular/forms';
import { WeatherService } from '../weather.service';
import { WeatherItem } from '../weather-item';
@Component({
selector: 'app-weather-search',
templateUrl: './weather-search.component.html',
styleUrls: ['../../assets/app.css'],
//providers: [WeatherService]
})
export class WeatherSearchComponent implements OnInit {
constructor(private _weatherService : WeatherService) { }
onSubmit(form : FormGroup){
//alert(form.value.location);
this._weatherService.searchWeatherData(form.value.location)
.subscribe(
data => {
const weatherItem = new WeatherItem(data.data.request["0"].query,data.data.weather["0"].maxtempC,data.data.weather["0"].maxtempC);
this._weatherService.addWeatherItems(weatherItem);
console.log(form);
})
}
ngOnInit() {
}
}
In this code snippet, we are injecting 'WeatherService' in the constructor. But is it possible to achieve the same result outside the constructor? What exactly is the role of the constructor here? Do we really need it in this context?