Answer the question
In order to leave comments, you need to log in
Angular2 - assignment in constructor in TypeScript how does it work?
Good day.
Can someone explain how to correctly write these lines without passing them to the constructor parameters?
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
@Injectable()
export class ApiService {
constructor(private router: Router) { }
get(){
this.router.navigate(['/test']);
}
}
private router: Http;
constructor() {
this.router = new Router();
}
Answer the question
In order to leave comments, you need to log in
private _http: Http;
constructor(http: Http) {
this._http = http;
}
Why do you need to inject into the method? Does this make any sense?
I think what you want can be done like this take.ms/Jt2pn. You need to use this.inject, and this injector appears in the class because of the @Injectable() decorator (@Directive and @Pipe inherit from @Injectable). When you inject into a constructor implicitly, this is what happens, very roughly:
@Injectable()
export class ApiService {
private _http: Http
constructor() {
this.injector = ReflectiveInjector.resolveAndCreate([Http]); // автоматически разрешает зависимости и заменяет new Http()
this._http = this.injector.get(Http) // получаем синглтон в пределах инжектора https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question