1

After this question, I have new a question. What is the difference between these two ways?

This was my initial code:

import {Http, HTTP_PROVIDERS} from 'angular2/http';

@Component({

viewProviders: [HTTP_PROVIDERS],
..//

constructor(http: Http){
..//

but while doing tests, They provided with codes to find the error:

import { Component, Inject} from 'angular2/core';
//above code should be at start.

constructor(@Inject(Http) http: Http) {

I think it works the same either way, someone could tell me, what is the difference, or just the first one is like the second but @Inject is implicit or something similar.Sorry for my English.

Community
  • 1
  • 1
Angel Angel
  • 19,670
  • 29
  • 79
  • 105

1 Answers1

2

In fact, @Inject decorator is used to ask for a dependency of a certain type. A string is also supported at this level.

If you already have a decorator of the class like Component or Injectable and you specify a type in TypeScript for the parameter (your case), using this other decorator isn't necessary because the resolution will be by class automatically. If you don't provide a type, the @Inject decorator will be useful...

Another use case. If you want to use ngUpgrade (hybrid Angular1 / Angular2 applications), factories of Angular1 are registered by name only and you can't resolve them by class. So using @Inject is necessary here. See this plunkr: http://plnkr.co/edit/yMjghOFhFWuY8G1fVIEg?p=preview. It's written in TypeScript but without annotation but can be adapted ;)

You could also have a look at this link:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • sorry but i am still confused is it necessary to provide at least one either `@component` or `@injectable` for angular2 ? – Pardeep Jain Feb 12 '16 at 05:22
  • 2
    To be able to inject something, you need a decorator at the level of the class. When the class is instantiated, the decorator will intercept the call and provide the excepted parameters using the current injector. @Inject allows to define more hints about what to inject when object types don't apply or if there is no type. – Thierry Templier Feb 12 '16 at 08:20
  • Interesting thing is that `Component({ ... })...` chain and `Inject` function are used in plunker example, instead of a real class and `@Component` and `@Inject` decorators. Was it done just to match ES5-ish style of code (doesn't seem appropriate because this is still TypeScript), or is there a necessity to do this here? – Estus Flask Feb 12 '16 at 10:32
  • Here there is no necessity to do that. With TypeScript, I see one use case (perhaps there are other) where @Inject is useful: to use forwardRef. – Thierry Templier Feb 12 '16 at 10:55