简体   繁体   中英

Why we need to inject service through constructor in angular2?

I'm learning Angular 2. And got confused over constructor. Consider the below code :

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() {
  }

}

Here we are injecting 'WeatherService' in constructor. Can't we do the same outside constructor ? What constructor is doing here actually? Do we really need it here?

The constructor itself is not doing actual work.
Angular creates a new WeatherSearchComponent executing

new WeatherSearchComponent(weatherService);

and this causes the constructor in WeatherSearchComponent to receive the weatherService value.

The constructor

constructor(private _weatherService : WeatherService)

causes an instance field _weatherService to be created and initialized with the value passed from DI.

The constructor is the only place where it is easy to know when the injected service is available and when not.

If the service would passed to a field, setter or method, code in the constructor could not access it because the constructor is executed before outside code has a change to set a field or call a method.

Also for code outside the constructor it is not safe to assume the service is available because this code could be called from the constructor before a field could be set from the outside.

For dependency injection passing dependencies to the constructor is the only way to avoid a lot of complexity.

Dependency Injection in constructor is always better option and while the component is getting created it will get the weatherService as a parameter. To make it clear, below is the transpiled code for your snippet.

var WeatherSearchComponent = (function () {
        function WeatherSearchComponent(_weatherService) {
            this._weatherService = _weatherService;
        }
        WeatherSearchComponent.prototype.onSubmit = function (form) {
            var _this = this;
            //alert(form.value.location);
            this._weatherService.searchWeatherData(form.value.location)
                .subscribe(function (data) {
                var weatherItem = new weather_item_1.WeatherItem(data.data.request["0"].query, data.data.weather["0"].maxtempC, data.data.weather["0"].maxtempC);
                _this._weatherService.addWeatherItems(weatherItem);
                console.log(form);
            });
        };
        WeatherSearchComponent.prototype.ngOnInit = function () {
        };
        WeatherSearchComponent = __decorate([
            core_1.Component({
                selector: 'app-weather-search',
                templateUrl: './weather-search.component.html',
                styleUrls: ['../../assets/app.css'],
            })
        ], WeatherSearchComponent);
        return WeatherSearchComponent;
    }());
    exports.WeatherSearchComponent = WeatherSearchComponent;

As you can see in turn the javascript code has weatherService Instance being passed on to the function weatherSearchComponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM