python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 2 @Inject vs @Injectable

Angular 2 @Inject vs. @Injectable [Why @Inject and @Injectable?]

What are the difference between @Inject and @Injectable?

@Inject() - Angular 2

Angular 2 @Inject() is a special technique for letting Angular know that a parameter must be injected.


Example as,

import { Inject } from '@angular/core';
import { Http } from '@angular/http';

class UserService {
  users:Array<any>;

  constructor(@Inject(Http) http:Http) {
    //TODO AS PER YOU.
  }
}

@Injectable() - Angular 2

@Injectable() marks a class as available to an injector for instantiation. An injector reports an error when trying to instantiate a class that is not marked as @Injectable().

How to use Dependency Injection (DI) correctly in Angular 2?

The basics Steps of Dependency injection,
1.      A class with @Injectable() to tell angular 2 that it’s to be injected “UserService”.
2.      A class with a constructor that accepts a type to be injected.

Example, UserService marked as @Injectable as,

import {Injectable, bind} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable() /* This is #Step 1 */
export class UserService {
  constructor(http: Http/* This is #Step 2 */ ) {
    this.http = Http;
  }
}

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions