Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @Inject and @Injectable in Angular 2 typescript

I don't understand When to use @Inject and when to use @Injectable ?

  import {Component, Inject, provide} from '@angular/core';
    import {Hamburger} from '../services/hamburger'; 
    export class App {
       bunType: string;
       constructor(@Inject(Hamburger) h) {
         this.bunType = h.bun.type;
       }
     }

And..

  import {Injectable} from '@angular/core';
    import {Bun} from './bun';
    @Injectable()
    export class Hamburger {
      constructor(public bun: Bun) {
      }
    }
like image 788
Sarvesh Yadav Avatar asked May 19 '16 06:05

Sarvesh Yadav


People also ask

What is difference between @inject and @injectable in Angular?

We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.

What does @inject do in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

What is inject in typescript?

The Typed Inject project focuses on type safety and explicitness. It uses neither decorators nor decorator metadata, opting instead for manually declaring dependencies. It allows for multiple DI containers to exist, and dependencies are scoped either as singletons or as transient objects.

What will @inject do?

4.1. The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms. A bean can only have one injectable constructor.


1 Answers

The @Injectable decorator aims to actually set some metadata about which dependencies to inject into the constructor of the associated class. It's a class decorator that doesn't require parameters. Without this decorator no dependency will be injected...

@Injectable()
export class SomeService {
  constructor(private http:Http) {
  }
}

The @Inject decorator must be used at the level of constructor parameters to specify metadata regarding elements to inject. Without it, the type of parameters is used (obj:SomeType is equivalent to @Inject(SomeType) obj).

@Injectable()
export class SomeService {
  constructor(@Inject(Http) private http:Http, @Inject('sometoken') obj) {
  }
}
like image 77
Thierry Templier Avatar answered Oct 10 '22 04:10

Thierry Templier