jmls
jmls

Reputation: 2969

angular2 : "import", inject and interfaces

I've been getting to grips with angular2, and whilst I have a good general understanding of the various concepts, DI and import are somewhat confusing.

To start with, I imported a class (let's call it "foo") into a component ("bar")

import { Component, OnInit } from '@angular/core';
import { Baz } from './foo';

@Component({
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
});

export class bar implements OnInit {
  private baz:Baz;

  ngOnInit():void {
    this.baz = new Baz();    
  }
}

Then I started reading about how bad this pattern was : if I needed to change the constructor of Baz, I would need to revisit all the code where Baz was "newed".

So, started to look at injecting Baz ..

I added @Injectable() to Baz, then changed the component to read

import { Component, OnInit } from '@angular/core';
import { Baz } from './foo';

@Component({
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css'],
  providers: [Baz]
});

export class bar implements OnInit {
  private baz:Baz;

  constructor(private baz:Baz) {}

  ngOnInit():void {}
}

This works just fine.

However, it started me thinking : the whole point of DI is meant to allow you / the application / the test framework to supply it's own version of "Baz" if needed.

So, the import { Baz } from './foo'; becomes problematical , as that is a "concrete" implementation and tied very much to a specific class.

After all that rambling, my questions are

Upvotes: 0

Views: 341

Answers (1)

Milad
Milad

Reputation: 28592

You should really read the Angular DI.

But to help you :

Should I be using interfaces instead of a direct import ? What do you mean ? There is no such a thing as Interface in javascript , that's just a fancy thing in Typescript which has only been created to help provide tooling .

Should the "providers" section be defined at the component, sub-module or module level ? - or does that depend on how widely "Baz" is being used ?

The further up to the root you provide an Injectable class , the more components further down would get the same instance.

You provide a IC (Injectable Class , E.g Service ) at root level , all the child component would get the samle instance unless they individually provide it.

So in short, if you don't provide, DI will look up your parent to find that service for you.

So, if you have a save service or such that the service itself does not contain any state, put it at root level , no need to be provided in component level.

Upvotes: 1

Related Questions