Angular 2 服務(wù)

2022-06-07 15:00 更新

描述

服務(wù)是僅負(fù)責(zé)執(zhí)行特定任務(wù)的JavaScript函數(shù)。 角度服務(wù)使用依賴注入機(jī)制注入,并包括應(yīng)用程序所需的值,函數(shù)或特性。 在Angular中沒(méi)有什么有關(guān)服務(wù),并且沒(méi)有ServiceBase類,但仍然可以將服務(wù)作為Angular應(yīng)用程序的基礎(chǔ)。

例子

下面的例子描述了在Angular 2中使用服務(wù):

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 Services</title>
    <!--Load libraries -->
    <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/service_main')
            .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>

上述代碼包括以下配置選項(xiàng):

  • 您可以使用typescript版本配置index.html文件。在使用transpiler選項(xiàng)運(yùn)行應(yīng)用程序之前,SystemJS將TypeScript轉(zhuǎn)換為JavaScript。

  • 如果在運(yùn)行應(yīng)用程序之前沒(méi)有翻譯到JavaScript,您可能會(huì)看到瀏覽器中隱藏的編譯器警告和錯(cuò)誤。

  • 當(dāng)設(shè)置emitDecoratorMetadata選項(xiàng)時(shí),TypeScript會(huì)為代碼的每個(gè)類生成元數(shù)據(jù)。如果不指定此選項(xiàng),將生成大量未使用的元數(shù)據(jù),這會(huì)影響文件大小和對(duì)應(yīng)用程序運(yùn)行時(shí)的影響。

  • Angular 2包括來(lái)自app文件夾的包,其中文件將具有.ts擴(kuò)展名。

  • 接下來(lái)它將從應(yīng)用程序文件夾加載主組件文件。如果沒(méi)有找到主要組件文件,那么它將在控制臺(tái)中顯示錯(cuò)誤。

  • 當(dāng)Angular調(diào)用main.ts中的引導(dǎo)函數(shù)時(shí),它讀取Component元數(shù)據(jù),找到“app”選擇器,找到一個(gè)名為app的元素標(biāo)簽,并在這些標(biāo)簽之間加載應(yīng)用程序。

要運(yùn)行代碼,您需要以下TypeScript(.ts)文件,您需要保存在應(yīng)用程序文件夾下。

metadata_main.ts
import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./app_service.component";    //importing component function

bootstrap(AppComponent);

現(xiàn)在我們將在TypeScript(.ts)文件中創(chuàng)建一個(gè)組件,我們將為該組件創(chuàng)建一個(gè)視圖。

app_service.component.ts
import {Component} from 'angular2/core';
import {MyListComponent} from "./service-list.component";

@Component({
    selector: 'my-app',
    template: `
    <country-list></country-list>
    `,
    directives: [MyListComponent]
})
export class AppComponent {
}
  • @Component是一個(gè)裝飾器,它使用配置對(duì)象來(lái)創(chuàng)建組件及其視圖。

  • 選擇器創(chuàng)建組件的實(shí)例,在父HTML中找到<my-app>標(biāo)記。

  • 接下來(lái)我們創(chuàng)建一個(gè)名為MyListComponent的指令,它將從service-list.component文件中訪問(wèn)。

service-list.component.ts
import {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<br>
   <ul>
      <li *ngFor="#cntry of countries">{{ cntry.name }}</li>
   </ul>
   `,
   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可以在模板中引用,并獲取數(shù)組的索引。 Angular 2將使用模板的局部變量綁定來(lái)自數(shù)組的模型名稱。

  • 我們有稱為提供程序的資源,它注冊(cè)在依賴注入的上下文中的類,函數(shù)或值。 可以使用country.service.ts文件中的@Injectable()注入名為CountryService的服務(wù)。

  • 接下來(lái)你使用OnInit鉤子在MyListComponent類中實(shí)現(xiàn),這表明Angular是創(chuàng)建組件的。 使用構(gòu)造函數(shù)調(diào)用_countryService并填充國(guó)家/地區(qū)列表。

  • 當(dāng)創(chuàng)建組件并評(píng)估輸入時(shí),調(diào)用 ngOnInit()鉤子。

country.service.ts
import {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.ts
import {Country} from "./country";

//storing array of data in Country
export const COUNTRIES: Country[] =[
   {name :"India"},
   {name: "Srilanka"},
   {name: "South Africa"},
   {name: "New Zealand"}
];
country.ts
export interface Country{
   name: string
}

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將上述HTML代碼另存為 index.html 文件,如同我們?cè)?a href="http://www.o2fo.com/angular2/angular2_environment.html" target="_blank">環(huán)境一章中創(chuàng)建的一樣,并使用上述 app i>文件夾,其中包含 .ts 文件。

  • 打開(kāi)終端窗口并輸入以下命令:

    npm start
  • 稍后,瀏覽器選項(xiàng)卡應(yīng)打開(kāi)并顯示輸出,如下所示。

,您可以以其他方式運(yùn)行此文件:

  • 將上面的HTML代碼另存為服務(wù)器根文件夾中的 angular2_services.html 文件。

  • 將此HTML文件打開(kāi)為http://localhost/angular2_services.html,并顯示如下所示的輸出。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)