如何在 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.