AVIL132016-11-30 16:25:49
AVIL13, 2016-11-30 16:25:49

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';

export class ApiService {
    constructor(private router: Router) { }


I tried to rewrite the constructor like this, so as not to pass Http in the class using this service.
I get an error and can't figure out how to write it correctly:
private router: Http;

constructor() {
    this.router = new Router();

How to rewrite the constructor and how to pass a parameter to it in the same scenario?
For an example where you can show how to do it right, I give this source .
Only two files are interesting in it:
app/route.click.ts - it has a go() method by which we go to the first page
app/layout/layout.component.ts - it is inherited from the above class, and it is necessary to call the parent go() method.
How to inject dependencies from app/route.click.ts without putting them in constructor parameters?
Thanks in advance.
Changed Http to Router in this example to make the example more detailed

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Sergey, 2016-11-30
Protko @Fesor

private _http: Http;

constructor(http: Http) {
    this._http = http;

Approach - Inversion of Control and Dependency Injection as an implementation of
the approach

Artem Kayun, 2016-12-01

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:

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

And how does the angular understand that this is not just a parameter, but di? The injector has a map in which dependencies are registered, the keys are the types of the injected classes, in this case Http.
In the official documentation, all this is written, it is understandable even with Google translator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question