Hello! I hope you have read our tutorial on Angular Components and Routing. In this article, we will continue discussing another interesting concept in Angular: services.
If Angular components are the presentation layer of our application, then what will be responsible for actually getting the real data and executing the business logic? This is where Angular services come in. The role of Angular services is to obtain, organize and ultimately share data, models and business logic across components.Before we dive into the technical details of Angular services, let’s first understand its functionality. This will help you understand which part of the code needs to be placed inside the component and which part needs to be placed inside the Angular service.
Here are some important facts about the service:
Services are defined using the
@Injectable decorator. This tells Angular that the service can be injected into components or other services. We'll discuss injecting services in detail later.
Service is a singleton class. Only a single instance of a specific service will run in your Angular application.
What is a service?
Dependency injection is used to introduce services inside the component.
Let us try to understand how to create a service and use it in an Angular component. You can find the complete source code for the project in our GitHub repository.Once you have the source code, navigate to the project directory and install the required dependencies using
npm install. After installing the dependencies, start the application by typing:
ng serve
https://localhost:4200/.
src --app ----components ------employee.component.css ------employee.component.html ------employee.component.ts ----services ------employee.service.spec.ts ------employee.service.ts ------employeeDetails.service.ts --app.routing.module.ts --app.component.css --app.component.html --app.component.spec.ts --app.component.ts --app.module.ts --assets --index.html --tsconfig.json
<path/service_name> command to automatically create a service. When using this method, you will automatically get the
.service.ts and .service.spec.ts files in the selected directory.
ng g service components/employee
.service.ts file has been created in your project structure, it's time to populate the contents of the service. To do this, you must decide what the service needs to do. Remember that you can have multiple services, each performing a specific business operation. In our case we will use employee.service.ts to return a static list of roles to any component that uses it.
Enter the following code inemployee.service.ts.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class EmployeeService { role = [ {'id':'1', 'type':'admin'}, {'id':'2', 'type':'engineer'}, {'id':'3', 'type':'sales'}, {'id':'4', 'type':'human_resources'} ] getRole(){ return this.role; } }
from the
@angular/core library. This is crucial because our service will be consumed or injected into the component.
@Injectable Instructions allow us to identify services.
decorator. The
providedIn property of
@Injectable specifies where the injector is available. Most of the time,
root is specified as its value. This means services can be injected at the application level. Other options are
any,
platform,
null, or
Type<any>.
. This class has a method
getRole, which returns a static array of objects.
@Component.
employee.component.ts and add the following code to it:
import { Component, OnInit } from '@angular/core'; import { EmployeeService } from '../services/employee.service'; @Component({ selector: 'employee', templateUrl: './employee.component.html' }) export class EmployeeComponent implements OnInit { role: any; constructor(private employeeService: EmployeeService) { } ngOnInit(): void { this.role = this.employeeService.getRole() } }
@Component
装饰器并调用它。我们指定 'employee'
作为选择器,并提供一个指向描述组件视图的 HTML 的模板 URL。OnInit
。因此,我们可以定义一个 ngOnInit
事件处理程序,该处理程序将在创建组件时调用。private employeeService: EmployeeService
。通过此步骤,我们将使该服务可以跨组件访问。ngOnInit
中获取数据。这可以变得更简单吗?由于该服务是一个单例类,因此可以在多个组件之间重用,而不会造成任何性能损失。
现在我们的组件中有数据了,让我们构建一个简单的 employee.component.html 文件来迭代角色并显示它们。下面,我们使用 *ngFor
来迭代角色,并仅向用户显示类型。
<h3>Data from employee.service</h3> <ul> <li *ngFor = "let role of roles">{{role.type}}</li> </ul>
在项目启动并运行之前我们只剩下一步了。我们需要确保 employee.component.ts 文件包含在 @NgModule
指令内的声明列表中。
如下所示,EmployeeComponent
已添加到 app.module.ts 文件中。
//app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EmployeeComponent } from './components/employee.component'; @NgModule({ declarations: [ AppComponent, EmployeeComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
有趣的是,我们尚未将该服务添加到我们的提供商列表中,但我们能够成功使用该服务。为什么?因为我们已经指定在应用程序的根级别提供服务(即使用 providedIn: 'root'
参数)。但是,请继续阅读以了解有关我们确实需要在 @NgModule
的 providers
数组中提及服务的场景的更多信息。
此外,我们还需要将 employee
元素添加到 app.component.html 文件中。
<h1> Tutorial: Angular Services </h1> <employee></employee> <router-outlet></router-outlet>
如果我们到目前为止运行我们的应用程序,它将如下所示:
现在,我们将获取特定于 employee.component.ts 的数据。
让我们创建一个新服务来从 API 获取数据。
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class EmployeDetailsService { fetchEmployeeDetailsURL = 'https://reqres.in/api/users?page=2' constructor(private http: HttpClient) { } fetchEmployeeDetails = () => { return this.http.get(this.fetchEmployeeDetailsURL); } }
现在,让我们逐行理解我们的代码。
HttpClient
非常重要。如果您是 HttpClient
的新手,您可以在本系列的另一篇文章中了解更多信息。EmployeeDetailsService
中,我们没有指定 provideIn
参数。这意味着我们需要执行额外的步骤来让整个应用程序了解我们的可注入服务。您将在下一步中了解这一点。HttpClient
本身就是一个可注入服务。在构造函数中声明它,以便将其注入到组件中。在 fetchEmployeeDetails
方法中,我们将使用 HttpClient.get
方法从 URL 获取数据。与我们的第一个服务不同,我们在 app.module.ts 中注册 EmployeeDetailsService
至关重要,因为我们尚未在根级别声明可注入。这是更新后的 app.module.ts 文件:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { EmployeeComponent } from './components/employee.component'; import { EmployeDetailsService } from './services/employeeDetails.service'; @NgModule({ declarations: [ AppComponent, EmployeeComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [ EmployeDetailsService], bootstrap: [AppComponent] }) export class AppModule { }
如果您密切关注,您可能会注意到两个重要的变化:
app.module.ts
文件中,我们需要将 EmployeDetailsService
包含在 Providers
列表中。@angular/common/http
导入 HttpClientModule
。 HttpClientModule
必须包含在我们的 imports
列表中。就是这样 - 我们现在准备在组件中使用 EmployeeDetailsService
。
为了适应新服务,我们将对组件进行一些更改。
首先,我们将在视图中添加一个按钮。当我们单击此按钮时,将通过 AJAX 调用加载数据。这是更新后的employee.component.html文件:
<h3>Data from employee.service</h3> <ul> <li *ngFor = "let role of roles">{{role.type}}</li> </ul>
接下来订阅EmployeDetailsService
中的getter函数。为此,我们将 EmployeDetailsService
添加到 employee.component.ts 中的构造函数中:
import { Component, OnInit } from '@angular/core'; import { EmployeeService } from '../services/employee.service'; import { EmployeDetailsService } from '../services/employeeDetails.service'; @Component({ selector: 'employee', templateUrl: './employee.component.html' }) export class EmployeeComponent implements OnInit { roles: any; employeeDetails: any; constructor(private employeeService: EmployeeService, private employeeDetailsService: EmployeDetailsService) { } ngOnInit(): void { this.roles = this.employeeService.getRole() } loadEmployeeDetails = () => { this.employeeDetailsService.fetchEmployeeDetails() .subscribe((response:any)=>{ this.employeeDetails = response.data; }) } }
完成此更改后,单击 LoadEmployeeDetails
按钮,我们将看到以下视图。
给你!我们已经逐步构建了一个可以处理静态和动态数据的 Angular 服务。现在,您应该能够构建自己的 Angular 服务并使用它们通过 AJAX 调用获取数据。您甚至可以以更可重用的方式实现业务逻辑。
The above is the detailed content of Angular Serving: A Comprehensive Guide for Beginners. For more information, please follow other related articles on the PHP Chinese website!