解释在Angular 2中创建服务的步骤

解释在Angular 2中创建服务的步骤

如果你曾经构建过一个组件,你就会知道,组件包含一个可执行的代码,允许你包含任何你想要的功能。组件的任务是实现用户体验,它将与用户互动。该组件将作为业务逻辑与应用程序视图之间的一个中间环节。然而,官方的Angular风格指南指出,将组件的逻辑限制在视图所需的范围内。服务应该处理所有其他的逻辑。组件代码中的代码主要用于控制和操作用户界面。它应该调用服务来提供与用户界面没有直接关系的功能。因此,如果所需的功能不是视图所需要的,你应该考虑建立一个服务。

服务被用来创建可以共享的变量/数据,并且可以在定义它的组件之外使用。一个服务本质上是一个具有特定目标的类。一个服务可以是一个变量、函数或应用程序需要的功能。我们经常使用服务来提供独立于组件的功能,在组件之间传输数据或逻辑,或者封装数据访问等外部交互。通过将这些活动从组件转移到服务,代码变得更容易测试、调试和重复使用。服务是一个可重用的功能片段,可以被各种组件使用。服务可以用来避免重写相同的代码,它可以被写一次,然后注入到所有使用该特定服务的组件中。

有必要对服务进行统一的负责。你不应该只是把所有的共享功能放到你的应用程序中的一个服务中。服务是额外的功能位,可以在应用中需要的时候和地方交付。我们通过将我们的服务与依赖性注入系统集成在Angular中来实现这一点。对于生成服务,我们可以遵循两种方式。

  • 通过手动创建它来执行特定任务,我们需要设置和配置服务。
  • 通过使用Angular CLI,它将自动设置服务的所有必要配置。

我们将通过实例依次了解这两种方法。

方法1:使用手动方式生成服务。

我们将创建服务类,使用装饰器来描述元数据,然后导入我们需要的东西。这些都是我们用来手动构建我们的组件和自定义管道的基本技术。

语法:

import { Injectable } from '@angular/core';  

@Injectable()  

export class ServiceName {  

}

让我们看看建立一个基本服务的代码,其功能是返回某个学院提供的课程列表。

第1步:创建一个CoursesService类,并将文件保存为courses.service.ts.别忘了导出该类,以便任何组件都可以使用该服务。让我们把我们的getdata方法添加到这个类中。

export class CoursesService {    // SERVICE CLASS

    constructor() { }

    getdata(): string[] {
        return ['C','C++', 'JAVA', 'Python'];
    }
}

第2步:服务元数据用装饰器进行装饰。我们在创建服务时使用Injectable装饰器。因为装饰器是一个函数,它应该被一个开放和关闭的括号所包围。

@Injectable()      // DECORATOR

export class CoursesService {

 constructor() { }

 getdata(): string[] {
   return ['C','C++', 'JAVA', 'Python'];
 }
}

第3步:确保定义了正确的导入。现在我们的服务类已经准备好了。

// IMPORT STATEMENT
import { Injectable } from '@angular/core';
  
@Injectable()
  
export class CoursesService {
  
    constructor() { }
  
    getdata(): string[] {
        return ['C','C++', 'JAVA', 'Python'];
    }
}

第4步:现在,我们需要注入我们的服务。该服务可以通过两种方式注入。

  • 注入为全局服务。将服务注入到根模块中,使其成为一个全局服务。这个模块中的任何组件现在都可以使用这个服务。
    import { BrowserModule } from "@angular/platform-browser";
    import { NgModule } from "@angular/core";
    import { AppComponent } from "./app.component";
    import { CoursesService } from "src/services/courses.service";
      
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      providers: [CoursesService], // FOR GLOBAL SERVICE
      bootstrap: [AppComponent],
    })
    export class AppModule {}
  • 作为本地服务注入。将服务直接注入到组件中,作为本地服务注入。
    import { Component } from "@angular/core";
    import { CoursesService } from "src/services/courses.service";
      
    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"],
      providers: [CoursesService], // FOR LOCAL SERVICE
    })
    export class AppComponent {}

第5步:在这一步,我们需要将服务导入到组件中,并使用该方法。

import { Component } from "@angular/core";
import { CoursesService } from "src/services/courses.service";
  
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  courses: string[];
  
  constructor(private _coursesService: CoursesService) {}
  
  ngOnInit() {
    this.courses = this._coursesService.getdata();
  }
}

第6步:更新HTML组件来渲染它。

<h2>Course List</h2>
<p *ngFor="let c of courses">{{ c }}</p>

第7步:运行”ng serve“来启动应用程序。我们将看到下面的输出。

解释在Angular 2中创建服务的步骤

方法2:使用Angular CLI生成服务。我们将在这里使用同样的例子来生成Angular CLI中的服务。

第1步:我们将使用Angular CLI来创建一个服务。建议使用这种方法,因为出错的机会较少。它只需要一个命令就可以完成任务。我们将按照下面的语法来创建一个服务。

语法:

ng g service courses

它将生成如下的服务代码骨架。

import { Injectable } from '@angular/core';  

@Injectable()

export class ServiceName {   
    constructor() { }
}

第2步:服务创建后,我们必须将其纳入app.module.ts的提供者。

providers: [CoursesService],

这里,服务名称的第一个字母应该是大写的,后面写上服务,没有任何空格。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CoursesService } from './courses.service';
  
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [CoursesService], //FOR GLOBAL SERVICE
  bootstrap: [AppComponent]
})
export class AppModule {}

第3步:app.component.ts中,做如下修改。

在其余所需的导入中导入该服务。

import { CoursesService } from './courses.service';

创建一个任何类型的变量:课程而不提及任何类型。

在构造函数中定义一个服务类型的属性

constructor(private _coursesService: CoursesService) {}

同时,创建一个ngOnInit方法。

ngOnInit() {
   this.courses = this._coursesService.getdata();
 }

完成上述任务后,app.component.ts文件将如下所示。

import { Component } from '@angular/core';
import { CoursesService } from './courses.service';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  courses: string[];
  
  constructor(private _coursesService: CoursesService) {}
  
  ngOnInit() {
    this.courses = this._coursesService.getdata();
  }
}

第4步:在这一步,我们将把我们的方法添加到服务中。

import { Injectable } from '@angular/core';  
  
@Injectable()  
  
export class CoursesService {  
      
    constructor() { }
      
    getdata(): string[] {
        return ['C','C++', 'JAVA', 'Python'];
    }
}

第5步:在app.component.html中,我们将打印存储在课程中的数据。

<h2>Course List</h2>
<p *ngFor="let c of courses">{{ c }}</p>

第6步:运行’ng serve’,将显示以下输出。

解释在Angular 2中创建服务的步骤

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程