如何在 Angular 8 中将服务注入到组件中?

angularjsweb developmentfront end technology

在 Angular 中,服务是单例对象,通常在整个 Angular 应用中只实例化一次。每个服务都包含多个方法,这些方法涵盖了一些功能。它是一种在一个或多个组件之间共享功能或职责的机制。

我们知道,使用 Angular 可以创建嵌套组件。一旦我们的应用嵌套起来,我们可能需要使用相同的功能。与其在多个组件中编写相同的代码,不如只编写一个地方,然后与其他组件共享数据。使用服务是处理这种情况的最佳方法。

在 Angular 的早期版本中,我们通常使用提供者、工厂、委托、值等来创建服务,而且也很清楚应该使用哪一个。

但是,在 Angular 8 中,创建服务的方式有两种,非常明确。

  • 使用 @Injector 装饰器创建服务

  • 向提供者注册类,或使用依赖注入注入类。

下面我们来看看如何在应用程序中定义服务。

我们可以根据需求创建自己的服务。要创建服务,请按照以下步骤操作。

  • 首先创建一个名称合适的 service.ts 文件。

  • 在此文件中,从 @angular/core 包导入 Injectable,并在类的开头添加 @Injectable 装饰器。

  • 导出类对象。

  • 这样我们就可以在其他组件中使用此服务。

  • 根据需求在导出的类对象中编写业务逻辑。

注意

当我们拥有带有提供者元数据的自定义服务时,我们需要在 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 提供了多种注册服务的方式。

  • 根级别的 ModuleInjector。

  • 平台级别的 ModuleInjector。

  • 使用 providers 元数据的 ElementInjector。

  • 使用 viewProviders 元数据的 ElementInjector。

  • NullInjector。

依赖注入

依赖注入是 Angular 框架的主要优势之一。

借助依赖注入(DI),我们可以将任何类型的依赖项(例如服务和外部模块)注入到应用程序中。为此,我们甚至不需要了解这些依赖模块或服务是如何开发的。

在 Angular 中,依赖注入包含三个部分:注入器(Injector)、提供器(Provider)和依赖项(Dependency)。

注入器用于提供对象或 API,这主要帮助我们创建依赖类或服务的实例。

提供器用于向注入器提供如何创建依赖对象实例的指令。提供器始终以令牌值作为输入,然后将该令牌值映射到新创建的类对象实例。

基本上,它的工作方式就像一位指导者。

依赖关系用于标识所创建对象的性质。

使用依赖注入 (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"; } }

这里没有指定根服务,因为我们想在特定组件中使用此服务,而不是作为根服务。因此,无需在 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

上文我们讨论了服务、依赖注入以及如何注入服务。服务用于创建共享数据。我们还可以通过将依赖服务注入组件和指令来实现代码重用。


相关文章