Home  >  Article  >  CMS Tutorial  >  Angular Serving: A Comprehensive Guide for Beginners

Angular Serving: A Comprehensive Guide for Beginners

王林
王林Original
2023-09-04 13:57:01524browse

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.

Services are where all business logic is held and shared across components. This makes your application more scalable and maintainable. Typically, services are also the correct place to interact with the backend. For example, if you need to make an AJAX call, you can create a method inside the service to complete the call.

Service is a singleton class. Only a single instance of a specific service will run in your Angular application.

What is a service?

A service in Angular is an object that is instantiated only once during the life cycle of the application. The data received and maintained by the service can be used throughout the application. This means that components can get data from the service at any time.

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

You should have the application running on

https://localhost:4200/.

The overall folder structure of our project is as follows.

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

1.Building the skeleton of the service

There are two ways to create services in Angular:

    Manually create folders and files within the project.
  1. Use the
  2. ng g service <path> command to automatically create a service. When using this method, you will automatically get the </path>.service.ts and .service.spec.ts files in the selected directory.
  3. ng g service components/employee 
    

2. Create service

Now that the

.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 in

employee.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;
  }
}

This service only returns a static list of roles to the application. Let's decode the service line by line.

    We import
  1. Injectable 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.
  2. Next, we apply the
  3. @Injectable 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>. </any>
  4. We create a class component named
  5. EmployeeService. This class has a method getRole, which returns a static array of objects.

3.Create component

As mentioned earlier, services in Angular are used to hold the business logic of the application. In order to display data to the viewer, we need a presentation layer. This is where traditional class-based Angular components come in, which are created using the decorator

@Component.

You can learn more about Angular components in the previous article in this series. It will help you understand Angular components and create your own. Create the file

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()
    }
 
}

Let’s break it down:

  1. 导入 @Component 装饰器并调用它。我们指定 'employee' 作为选择器,并提供一个指向描述组件视图的 HTML 的模板 URL。
  2. 声明组件类并指定它实现 OnInit。因此,我们可以定义一个 ngOnInit 事件处理程序,该处理程序将在创建组件时调用。
  3. 为了使用我们的服务,必须在构造函数内声明它。在我们的例子中,您将在构造函数中看到 private employeeService: EmployeeService 。通过此步骤,我们将使该服务可以跨组件访问。
  4. 由于我们的目标是在创建员工组件时加载角色,因此我们在 ngOnInit 中获取数据。

这可以变得更简单吗?由于该服务是一个单例类,因此可以在多个组件之间重用,而不会造成任何性能损失。

4.创建视图

现在我们的组件中有数据了,让我们构建一个简单的 employee.component.html 文件来迭代角色并显示它们。下面,我们使用 *ngFor 来迭代角色,并仅向用户显示类型。

<h3>Data from employee.service</h3>
<ul>
    <li *ngFor = "let role of roles">{{role.type}}</li>
</ul>

5.运行项目

在项目启动并运行之前我们只剩下一步了。我们需要确保 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' 参数)。但是,请继续阅读以了解有关我们确实需要在 @NgModuleproviders 数组中提及服务的场景的更多信息。

此外,我们还需要将 employee 元素添加到 app.component.html 文件中。

<h1>
  Tutorial: Angular Services
</h1>
<employee></employee>

<router-outlet></router-outlet>

如果我们到目前为止运行我们的应用程序,它将如下所示:

Angular 服务:初学者综合指南

6.从服务动态获取数据

现在,我们将获取特定于 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);
    }
}

现在,让我们逐行理解我们的代码。

  1. 由于我们要通过 AJAX 调用获取数据,因此导入 HttpClient 非常重要。如果您是 HttpClient 的新手,您可以在本系列的另一篇文章中了解更多信息。
  2. 在我们的 EmployeeDetailsS​​ervice 中,我们没有指定 provideIn 参数。这意味着我们需要执行额外的步骤来让整个应用程序了解我们的可注入服务。您将在下一步中了解这一点。
  3. HttpClient 本身就是一个可注入服务。在构造函数中声明它,以便将其注入到组件中。在 fetchEmployeeDetails 方法中,我们将使用 HttpClient.get 方法从 URL 获取数据。

7.app.module 中注册服务

与我们的第一个服务不同,我们在 app.module.ts 中注册 EmployeeDetailsS​​ervice 至关重要,因为我们尚未在根级别声明可注入。这是更新后的 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 { }

如果您密切关注,您可能会注意到两个重要的变化:

  1. 在我们的 app.module.ts 文件中,我们需要将 EmployeDetailsS​​ervice 包含在 Providers 列表中。
  2. 我们需要从 @angular/common/http 导入 HttpClientModuleHttpClientModule 必须包含在我们的 imports 列表中。

就是这样 - 我们现在准备在组件中使用 EmployeeDetailsS​​ervice

8.获取动态数据

为了适应新服务,我们将对组件进行一些更改。

添加一个按钮来加载数据

首先,我们将在视图中添加一个按钮。当我们单击此按钮时,将通过 AJAX 调用加载数据。这是更新后的employee.component.html文件:

<h3>Data from employee.service</h3>
<ul>
    <li *ngFor = "let role of roles">{{role.type}}</li>
</ul>

  • {{employee.email}}

订阅Getter函数

接下来订阅EmployeDetailsS​​ervice中的getter函数。为此,我们将 EmployeDetailsS​​ervice 添加到 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 服务。现在,您应该能够构建自己的 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn