Coding With Fun
Home Docker Django Node.js Articles FAQ

Angular 2 relies on injection


May 08, 2021 Angular2


Table of contents


Describe

Dependency injection is a powerful model for managing code dependencies.

Dependency injection is a design pattern that passes objects as dependencies in different components of an application. I t creates a new class instance and its required dependencies. Dependency injection is stimulated into the framework and can be used anywhere.

When using dependency injection, you must keep the following in mind:

  • The injector mechanism maintains service instances and can be created using providers.

  • Providers are a way to create services.

  • You can register the provider with the injector.

Example

The following example describes the use of dependency injection in Angle 2:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Dependency Injection</title>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/dependency_injection_main')
            .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>

The above code includes the following configuration options:

  • You can configure index files using the .html version. SystemJS converts TypeScript to JavaScript before running the application using the transpiler option.

  • If you don't translate to JavaScript before you run your application, you may see compiler warnings and errors hidden in your browser.

  • TypeScript generates metadata for each class of your code when you set the emitDecorator Metadata option. If you do not specify this option, a large amount of unused metadata is generated, which affects the file size and the application runtime.

  • Angular 2 includes packages from the app folder, Chinese will have a .ts extension.

  • Next it loads the main component file from the application folder. If the primary component file is not found, it displays an error in the console.

  • When Angula called the boot function in main.ts, it reads the Company metadata, finds the "app" selector, finds an element label named app, and loads the application between those tags.

Let's create TypeScript (.ts) files and save them in the app folder.

dependency_injection_main.ts
import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./fruit-component";          //importing component function

bootstrap(AppComponent);
fruit-component.ts
import {Component} from 'angular2/core';
import {MyListComponent}  from './play-component';

//@Component is a decorator that uses configuration object to create the component and its view.
@Component({
  selector: 'my-app',   //The selector creates an instance of the component where it finds 'my-app' tag in parent HTML
  template:`<my-list></my-list>`,
  directives:[MyListComponent]  //'MyListComponent' is the root component of fruits that governs child components
})
export class AppComponent { }
play-component.ts
import {Component} from "angular2/core";
import {FruitService} from "./fruits.service";
import {Fruits} from "./fruits";
import {OnInit} from "angular2/core";

@Component({
   selector: "my-list",
   template: ` List of Fruits<br>
   <ul>
      <li *ngFor="#list of fruits">  //The NgFor directive instantiates a template once per item from an iterable
         {{list.id}} - {{ list.name }}
      </li>
   </ul>
   `,
   providers: [FruitService]  //providers are part of @Component metadata
})

//The 'MyListComponent' should get list of fruits from the injected 'FruitService'
export class MyListComponent implements OnInit {
   public fruits : Country[];

   //Using constructor, call the _fruitService and populate the fruits list
   constructor(private _fruitService: FruitService) {}

   getContacts(){
      this._fruitService.getContacts().then((fruits: Country[]) => this.fruits = fruits);
   }

   //The 'ngOnInit()' hook is called when done with creating the component and evaluated the inputs
   ngOnInit():any{
      this.getContacts();
   }
}
fruits.service.ts
import {Injectable} from "angular2/core";
import {COUNTRIES} from "./fruits.lists";

//It is used for meta data generation and specifies that class is available to an injector for instantiation
@Injectable()

//'FruitService' exposes 'getContacts()' method that returns list of data
export class FruitService {
   getContacts() {
      return Promise.resolve(COUNTRIES); // takes values from fruits.lists.ts file
   }
}
fruits.lists.ts
import {Fruits} from "./fruits";

//storing array of data in Fruits
export const COUNTRIES: Fruits[] =[
   {"id": 1, name :"Apple"},
   {"id": 2, name: "Grapes"},
   {"id": 3, name: "Orange"},
   {"id": 4, name: "Banana"}
];
fruits.ts
export interface Fruits{
   id: number;
   name: string;
}

Output

Let's take the following steps to see how the code above works:

  • Save the HTML code above as an index .html file, as we created in the Environment section, and use the application folder above that contains the .ts file.

  • Open the terminal window and enter the following command:

    npm start
  • Later, the browser tab should open and display the output, as shown below.

Or you can run the file in another way:

  • Save the HTML code above as angular2_dependency_injection.html file in the server root folder.

  • Open this HTML file as http://localhost/angular2_dependency_injection.html and display the output as shown below.

Related tutorials

HTML tutorial