[Angular 2] 翻译:Angular 2 服务:是不是单例?

原文出处:http://www.itnose.net/detail/6610731.html

这篇文章的目的是帮助大家理解 Angular 2 基于依赖注入的作用域如何工作,需要明白组件,服务等相关知识以及对依赖注入的基本了解。

– Angular 2 服务是不是单例?

– 某种意义上来说,是的。。。

– 兄弟,你说的貌似没什么帮助啊。。。

– 那好吧,让我们从头说起。。。

Angular 1.x 服务非常流行。每一个服务都有一个具体实例,它可以被注入并在需要使用的地方来使用。Angular 2 的服务也照样不错,让我们探讨这个话题吧。

– 兄弟,是时候言归正传啦。。。

– 好的,让我们先从一个简单的服务开始说起,这是让人难以忘记的反例家族的一员。。。

服务尽可能简单

// a very simple counter service
import { Injectable } from '@angular/core';
 
@Injectable()
export class SimpleCounterService {
  private count: number = 0;
 
  inc() {
    this.count++;
  }
 
  dec() {
    this.count--;
  }
 
  getCount(): number {
    return this.count;
  }
} 
 

如果我们想在整个应用程序中使用这个服务,就像我们在 Angular 1 做的那样。我们不需要做更多,只是把它作为 BootStrap 方法的第二个参数就行。

bootstrap(App, [CounterService]);
 

接下来,我们可以使用任何有用的服务使用任何的组件,比如:

import { Component } from '@angular/core';
import { SimpleCounterService } from './simple_counter.service';
 
@Component({
  selector: 'simple-counter',
  template: `
    <divclass="simple-counter">
      <button (click)="dec()">-</button>
        {{ getCount() }}
      <button (click)="inc()">+</button>
    </div>
  `
})
export class SimpleCounterComponent {
  constructor(private counterService: SimpleCounterService) {
  }
 
  dec() {
    this.counterService.dec();
  }
 
  inc() {
    this.counterService.inc();
  }
 
  getCount(): number {
    return this.counterService.getCount();
  }
}
 

非常简单。

– 兄弟,这没意义啊。每个计数器组件的值都是一样的,如果我需要更多的计数器呢?

– 说的很对。当我们遇到一个这样的服务时,这是最重要的问题之一。让我们采用在 Angular 1 解决该问题的方案:给每个计数器一个唯一标识符。。。

经过唯一标识符处理过的服务

我们的服务。。。

// a very simple counter service
import { Injectable } from '@angular/core';
 
@Injectable()
export class OldschoolCounterService {
  private counters = {};
 
  inc(counterId) {
    this.getCounterById(counterId).count++;
  }
 
  dec(counterId) {
    this.getCounterById(counterId).count--;
  }
 
  getCount(counterId): number {
    return this.getCounterById(counterId).count;
  }
 
  deleteCounter(counterId) {
    deletethis.counters[counterId];
  }
 
  private getCounterById(id): Object {
    if (! this.counters[id]) {
      this.counters[id] = { count: 0 };
    }
    return this.counters[id];
  } 
}
 

不要忘记使用 bootstrap 方法:

bootstrap(App, [OldschoolCounterService]);
 

我们的组件。。。

import { Component, Input, OnDestroy } from '@angular/core';
import { OldschoolCounterService } from './oldschool_counter.service';
 
@Component({
  selector: 'oldschool-counter',
  template: `
    <divclass="simple-counter">
      <button (click)="dec()">-</button>
        {{ getCount() }}
      <button (click)="inc()">+</button>
    </div>
  `
})
export class OldschoolCounterComponent implements OnDestroy {
  @Input() private counterId: string;
 
  constructor(private counterService: OldschoolCounterService) {
  }
 
  dec() {
    this.counterService.dec(this.counterId);
  }
 
  inc() {
    this.counterService.inc(this.counterId);
  }
 
  getCount(): number {
    return this.counterService.getCount(this.counterId);
  }
 
  ngOnDestroy() {
    // we do not want to remember the state of the component,
    // so we delete the counter from the service
    this.counterService.deleteCounter(this.counterId);
  }
}
 

– 现在运行得不错,就像我们想要的那样,每个计数器都有不同的值

– 是的,但是。。。

– 我不觉得还有什么问题啊。。。

– 灵活性和可复用性怎么样?

– 我觉得还好吧。我只是刚设置了ID,哦,如果。。。

– 对,就是这个。

这不是这儿唯一的问题。最明显的问题在于我们需要非常小心,不能使用相同的 ID 给不同的组件。这个问题还好解决。更大的问题在于耦合在一起的组件和服务不严密。组件需要提供一个 ID,服务总是需要基于该 ID 来运行。所以我们用特定方法来限制从而实施该服务。

– 好,那该怎么做?

– 这是 Angular 2 采用的方法:正如我之前提到的 Angular 2 的服务是某种单例。。。让我们来看看到底是什么意思

Angular 2 方式的服务

在 Angular 2 中,服务是单例 scopewise 的。

– 为你的健康干杯!

装饰器组件有一个叫 providers 的属性。它工作方式完全和 bootstrap 函数第二个参数相同,但是该服务在组件范围内建立了一个新的实例,因此,组件与每个下级组件都会使用这个新的实例。(除非他们不使用自有的服务上的实例,不过这就另说啦。)

让我们看看新的计数组件。。。

import { Component } from '@angular/core';
import { SimpleCounterService } from './simple_counter.service';
 
@Component({
  selector: 'newage-counter',
  template: `
    <divclass="newage-counter">
      <button (click)="dec()">-</button>
        {{ getCount() }}
      <button (click)="inc()">+</button>
    </div>
  `,
  providers: [
    SimpleCounterService
  ]
})
export class NewageCounterComponent {
  constructor(private counterService: SimpleCounterService) {
  }
 
  dec() {
    this.counterService.dec();
  }
 
  inc() {
    this.counterService.inc();
  }
 
  getCount(): number {
    return this.counterService.getCount();
  }
}
 

– 那服务呢?

– 我们简单地使用 SimpleCounterService 就好啦。

由于我们在组件中有一个专门的实例服务,每个组件将会有自身的值。

就像我们看到的 scopewise 单例服务设计模式是 Angular 2 的一个令人难以置信的功能。它给代码更多的灵活性,使其更容易重用及维护。而且我们只是说了表面上的一点点。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值