例子:
import { Injectable } from '@angular/core';
let count = 0;
@Injectable()
export class MyService {
seed: number;
_count: number;
constructor(){
this.seed = Number((Math.random() * 100).toFixed(0));
this._count = count++;
console.log('diablo constructor called: ' + this.seed);
}
}
Service构造函数的断点只触发了一次:
这个单例行为在Angular DI帮助文档里有提到:
https://angular.io/guide/glossary#injector
什么时候会失去单例的特性呢?看这个例子:
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
seed: number;
constructor(){
this.seed = Number((Math.random() * 100).toFixed(0));
console.log('diablo constructor called: ' + this.seed);
}
}
@Injectable()
export class MyNewService {
seed: number;
text: 'NewService';
constructor(){
this.seed = Number((Math.random() * 100).toFixed(0));
console.log('diablo constructor called: ' + this.seed);
}
}
NgModule里的定义:
表面上看,请求MyService时,也使用MyNewService进行类的实例化,似乎我们会得到MyNewService的单例。
constructor(old: MyService, newS: MyService) {
this.test();
console.log('ok');
}
其实不然,测试发现:我们得到了两个不同的MyNewService实例:
根据token(MyService)拿到factory(MyNewService_Factory):
第二次触发,token变成了MyNewService:
用了useExisting之后的效果:
网友评论