如何在 Angular 8 中將服務注入元件?


在 Angular 中,服務是單例物件,通常只為整個 Angular 應用程式例項化一次。每個服務都包含多個方法,其中包括一些要執行的功能。它是一種在多個元件之間共享功能或職責的機制。

我們知道,使用 Angular 可以建立基於巢狀的元件。一旦我們的應用程式巢狀,我們可能需要使用相同的功能。與其在多個元件中編寫相同的程式碼,不如在一個地方編寫程式碼,然後與不同的元件共享資料。使用服務來處理這個問題是最好的方法。

在 Angular 的早期版本中,我們習慣於使用提供程式、工廠、委託、值等來建立服務,而且也清楚地知道需要使用哪一個。但是,在 Angular 8 中,它使透過以下兩種方式建立服務變得清晰。

  • 使用 @Injector 裝飾器建立服務

  • 使用依賴注入註冊類或注入類。

讓我們看看如何在我們的應用程式中定義服務。

我們可以根據需要建立自己的服務。要建立服務,請按照以下步驟操作。

  • 首先建立一個名為 service.ts 的檔案。

  • 在這個檔案中,從 @angular/core 包匯入 Injectable 並將 @Injectable 裝飾器提供在類的開頭。

  • 匯出類物件。這樣我們就可以在其他元件中使用此服務。

  • 根據需求在匯出的類物件中編寫業務邏輯。

注意

當我們有自己的帶有 provider 元資料的服務時,我們需要在 app.module.ts 檔案中匯入它才能使用這些服務功能。如果我們沒有匯入建立的服務,它將對整個應用程式不可見。如果我們只在一個元件中匯入建立的服務而沒有在主模組中匯入它,則該服務只對該特定元件可用。如果我們在主模組中提供服務,則將為整個應用程式建立服務的唯一例項。

示例

在 app 資料夾內建立一個服務類,名為 **messageService.service.ts**。

在建立的服務類中編寫如下所示的程式碼。

import { Injectable } from '@angular/core'; @Injectable() export class MessageService { constructor() { } sendMessage(message: string) { return "Hello"; } };

在這裡,**@Injectable** 裝飾器將一個普通的 TypeScript 類轉換為 Angular 服務。

註冊服務

要使用依賴注入,需要註冊服務。Angular 提供多種註冊服務的方法。

  • 模組注入器 @ 根級別。

  • 模組注入器 @ 平臺級別。

  • 使用 providers 元資料的元素注入器。

  • 使用 viewProviders 元資料的元素注入器。

  • NullInjector。

依賴注入

依賴注入是 Angular 框架的主要優勢之一。藉助此 DI,我們可以將任何型別的依賴項(如服務、外部模組)注入到我們的應用程式中。為此,我們甚至不需要知道這些依賴模組或服務是如何開發的。

在 Angular 中,依賴注入包含三個部分:注入器、提供程式和依賴項。

注入器用於公開一個物件或 API,這些物件或 API 主要幫助我們建立依賴類或服務的例項。

提供程式用於向注入器提供有關如何建立依賴物件例項的指令。提供程式始終將令牌值作為輸入,然後將該令牌值與新建立的類物件的例項對映。基本上,它像一個指導者。

依賴項用於標識建立的物件的性質。

使用 DI,

  • 我們可以在建構函式級別使用 provider 元資料建立服務類的例項。

  • 當我們需要時,DI 提供依賴類的例項的引用程式碼。

  • 所有依賴注入物件的例項都作為單例物件建立。

讓我們看看普通服務和使用提供程式注入服務的示例。

示例:注入到模組

建立一個服務類並新增一些功能。

這裡我使用的是在 app 資料夾中建立的相同服務,即 **messageService.ts** 檔案。

import { Injectable } from '@angular/core'; @Injectable(){ providedIn: "root" } export class MessageService { constructor() { } sendMessage (message: string) { return "Hello! Message from Angular Service"; } };

我們現在有了服務類,將其匯入到 **app.module.ts** 檔案中。

import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppComponent } from "./app.component"; import { MessageService } from "./messageService"; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [MessageService], bootstrap: [AppComponent] }) export class AppModule {}

現在,讓我們匯入服務類,從服務獲取資料並在 UI 中顯示。

在 **app.component.ts** 檔案中編寫如下所示的程式碼。

import { Component } from '@angular/core'; import { MessageService } from './messageService'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { message: string = ""; constructor(private messageService: MessageService ) {} ngOnInit() { this.message = this.messageService.sendMessage(); } }

在 app.component.html 檔案中

<p>Service Example</p> <p>{{message}}</p>

輸出

Service Example
Hello! Message from Angular Service

示例:將服務注入元件

服務類:**messageService.ts** 檔案

import { Injectable } from "@angular/core"; @Injectable() export class MessageService { constructor() {} sendMessage(message: string) { return "Message from Angular Service"; } }

這裡沒有指定 root,因為我們想在這個特定元件中使用此服務。不是作為根服務。因此,無需匯入到 **app.module.ts** 檔案中。

直接注入到所需的元件中。這裡我將服務類注入到 **app.component.ts** 檔案中。

import { Component } from '@angular/core'; import { MessageService } from './messageService'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { message: string = ""; constructor(private messageService: MessageService ) {} ngOnInit() { this.message = this.messageService.sendMessage(); } }

在 **app.component.html** 檔案中。編寫如下所示的程式碼。

<p>Service Example</p> <p>{{message}}</p>

在這裡,我們可以看到,我們將服務類注入到模組級別或僅注入到元件中。如果我們將服務注入到任何特定元件中,我們將只能在該特定元件中使用它。

輸出

Service Example
Message from Angular Service

上面我們討論了服務、依賴注入以及如何注入服務。服務用於建立共享資料。我們還可以透過將依賴服務注入到元件和指令中來實現程式碼可重用性。

更新於:2023年2月21日

4K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.