Angular2服务

Angular 2 服务

描述服务是仅负责执行特定任务的JavaScript函数。 角度服务使用依赖注入机制注入,并包括应用程序所需的值,函数或特性。 在Angular中没有什么有关服务,并且没有ServiceBase类,但仍然可以将服务作为Angular应用程序的基础。例子下面的例子描述了在Angular 2中使用服务:<!DOCTYPE html>

<html>

<head>

<title>Angular 2 Services</title>

<!--Load libraries -->

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"&gt;&lt;/script&gt;

<script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"&gt;&lt;/script&gt;

<script>

System.config({

transpiler: 'typescript',

    typescriptOptions: { emitDecoratorMetadata: true },

packages: {'app': {defaultExtension: 'ts'}}

});

System.import('/angular2/src/app/service_main')

.then(null, console.error.bind(console));

&lt;/script&gt;

</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)文件,您需要保存在应用程序文件夹下。metadata_main.tsimport {bootstrap} from 'angular2/platform/browser'; //importing bootstrap function

import {AppComponent} from "./app_service.component"; //importing component function

bootstrap(AppComponent);

现在我们将在TypeScript(.ts)文件中创建一个组件,我们将为该组件创建一个视图。app_service.component.tsimport {Component} from 'angular2/core';

import {MyListComponent} from "./service-list.component";

@Component({

selector: 'my-app',

template: &lt;country-list&gt;&lt;/country-list&gt; ,

directives: [MyListComponent]

})

export class AppComponent {

}

@Component是一个装饰器,它使用配置对象来创建组件及其视图。 选择器创建组件的实例,在父HTML中找到<my-app>标记。 接下来我们创建一个名为MyListComponent的指令,它将从service-list.component文件中访问。 service-list.component.tsimport {Component} from "angular2/core";

import {CountryService} from "./country.service";

import {Contact} from "./country";

import {OnInit} from "angular2/core";

@Component({

selector: "country-list",

template: List of Countries&lt;br&gt; &lt;ul&gt; &lt;li *ngFor="#cntry of countries"&gt;{{ cntry.name }}&lt;/li&gt; &lt;/ul&gt; ,

providers: [CountryService]

})

export class MyListComponent implements OnInit {

public countries : Country[];

constructor(private _countryService: CountryService) {}

getContacts(){

this._countryService.getContacts().then((countries: Country[]) => this.countries = countries);

}

ngOnInit():any{

this.getContacts();

}

}

局部变量cntry可以在模板中引用,并获取数组的索引。 Angular 2将使用模板的局部变量绑定来自数组的模型名称。 我们有称为提供程序的资源,它注册在依赖注入的上下文中的类,函数或值。 可以使用country.service.ts文件中的@Injectable()注入名为CountryService的服务。 接下来你使用OnInit钩子在MyListComponent类中实现,这表明Angular是创建组件的。 使用构造函数调用_countryService并填充国家/地区列表。 当创建组件并评估输入时,调用 ngOnInit()钩子。 country.service.tsimport {Injectable} from "angular2/core";

import {COUNTRIES} from "./country.contacts";

//@Injectable() specifies class is available to an injector for instantiation and an injector will display an error when trying to instantiate a class that is not marked as @Injectable()

@Injectable()

//CountryService exposes the getContacts() method that returns the data

export class CountryService {

getContacts() {

return Promise.resolve(COUNTRIES); // takes values from country.contacts typescript file

}

}

country.contacts.tsimport {Country} from "./country";

//storing array of data in Country

export const COUNTRIES: Country[] =[

{name :"India"},

{name: "Srilanka"},

{name: "South Africa"},

{name: "New Zealand"}

];

country.tsexport interface Country{

name: string

}

输出让我们执行以下步骤,看看上面的代码如何工作:将上述HTML代码另存为 index.html 文件,如同我们在环境一章中创建的一样,并使用上述 app i>文件夹,其中包含 .ts 文件。 打开终端窗口并输入以下命令: npm start 稍后,浏览器选项卡应打开并显示输出,如下所示。或,您可以以其他方式运行此文件:将上面的HTML代码另存为服务器根文件夹中的 angular2_services.html 文件。 将此HTML文件打开为http://localhost/angular2_services.html,并显示如下所示的输出。