Angular 2 依赖注入
描述依赖注入是一个用来管理代码依赖的强大模式。依赖注入是一种将对象作为应用程序中不同组件中的依赖关系传递的设计模式。 它创建一个新的类实例及其所需的依赖项。 依赖注入被刺激到框架中,并且可以在任何地方使用。使用依赖注入时,必须记住以下几点:注入器机制维护服务实例,并且可以使用提供者创建。提供者是创建服务的一种方式。您可以与注入器一起注册提供程序。例子下面的例子描述了在Angular 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>
上述代码包括以下配置选项: 您可以使用typescript版本配置index.html文件。在使用transpiler选项运行应用程序之前,SystemJS将TypeScript转换为JavaScript。 如果在运行应用程序之前没有翻译到JavaScript,您可能会看到浏览器中隐藏的编译器警告和错误。 当设置emitDecoratorMetadata选项时,TypeScript会为代码的每个类生成元数据。如果不指定此选项,将生成大量未使用的元数据,这会影响文件大小和对应用程序运行时的影响。 Angular 2包括来自app文件夹的包,其中文件将具有.ts扩展名。 接下来它将从应用程序文件夹加载主组件文件。如果没有找到主要组件文件,那么它将在控制台中显示错误。 当Angular调用main.ts中的引导函数时,它读取Component元数据,找到“app”选择器,找到一个名为app的元素标签,并在这些标签之间加载应用程序。 让我们创建TypeScript(.ts)文件并将它们保存在app文件夹中。dependency_injection_main.tsimport {bootstrap} from 'angular2/platform/browser'; //importing bootstrap function
import {AppComponent} from "./fruit-component"; //importing component function
bootstrap(AppComponent);
fruit-component.tsimport {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.tsimport {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.tsimport {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.tsimport {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.tsexport interface Fruits{
id: number;
name: string;
}
输出让我们执行以下步骤,看看上面的代码如何工作:将上面的HTML代码保存为index.html文件,如同我们在环境章节中创建的,并使用上面的包含.ts文件的应用程序文件夹。 打开终端窗口并输入以下命令: npm start 稍后,浏览器选项卡应打开并显示输出,如下所示。或者你可以用另一种方式运行这个文件:将以上HTML代码作为angular2_dependency_injection.html文件保存在服务器根文件夹中。将此HTML文件打开为http://localhost/angular2_dependency_injection.html,并显示如下所示的输出。相关教程HTML教程