[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 方法: 我们的组件。。。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); } } |