{% raw %}
Angular 服务示例
通过示例学习创建 Angular 服务并将服务作为全局依赖项(通过模块)与局部依赖项(通过组件)导入。
Table of ContentsCreate ServiceGlobal service vs Local Service InjectionDemo
创建服务
在所需位置创建一个新文件calc.service.ts,并将以下代码放入其中。 CalcService是服务名称。
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})export class CalcService {constructor() { }}
以上服务非常完整,可以在应用组件中使用。
使用 Angular CLI
如果使用 Angular CLI,创建服务很容易。 这只是一个命令,可以完成所有工作。 它将像上面的示例一样生成服务代码。
$ ng g s service/calc --flat//Other useful options--force = override--spec=false = dont generate spec file--dry-run = dont touch code if it has been updated already.
全局服务与本地服务注入
要注入服务,您有两个选择。
1)注入为“全局服务”
要作为全局服务注入,请将服务注入到根模块中。
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppComponent } from './app.component';import { CalcService } from './service/calc.service';@NgModule({declarations: [AppComponent],imports: [BrowserModule],providers: [CalcService],bootstrap: [AppComponent]})export class AppModule { }
2)注入为“本地服务”
要作为本地服务注入,请直接将服务注入组件。
import { Component } from '@angular/core';import { CalcService } from './service/calc.service';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'],providers: [CalcService]})export class AppComponent {title = 'app';constructor(calc:CalcService){//Use calc}}
演示
1)添加服务方法
为了演示CalcService的用法,我们在服务中定义一个新方法,并在app.component.ts中使用它。
我添加了方法add(),该方法将剩余参数用作数字数组。 然后,将所有数字相加并返回总和。
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})export class CalcService {constructor() { }public add(...params: number[]): number {let result = 0;for (let val of params) {result += val;}return result;}}
2)将服务导入到组件并使用该方法更新模型
我创建了一个新的模型属性'sum',我们将使用服务方法add()的返回值进行更新。
import { Component } from '@angular/core';import { CalcService } from './service/calc.service';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})export class AppComponent {title = 'app';sum: number = 0;constructor(calc:CalcService){this.sum = calc.add(1,2,3,4);}}
3)更新视图 HTML
现在,最后,使用新添加的模型属性sum更新视图html文件。
<h1>Welcome to {{ title }}!Sum is {{sum}}</h1>
4)运行应用
现在,使用命令'ng serve'运行该应用,并检查'http://localhost:4200/'的输出。

Angular 2 服务输出
将我的问题放在评论部分。
学习愉快!
{% endraw %}
