据我了解Angular 2服务,如果您在根组件中注入一个,则所有子组件共享该服务的相同实例。
我有一个我想在装饰器和应用程序中使用的日志记录服务。但我想重用根组件中的现有服务实例。
现在,如果我在日志服务构造函数中放置一个调试器语句,我的服务会被多次实例化。我使用ReflectiveInjector
,但我认为它创建了一个新实例,而不是使用全局实例。
也许我正在犯这个错误,或者我缺乏理解。我这样做的原因是因为我在日志记录服务中有一个可观察的流,并且多个实例创建了多个observable。
@Injectable()
export class LoggerService {
private _applicationLog$: ReplaySubject<string>;
get applicationLog$(): Observable<string> {
return this._applicationLog$.asObservable();
}
constructor(private $localStorage: LocalStorageService, private $appSettings: AppSettings) {
this._applicationLog$ = <ReplaySubject<string>>new ReplaySubject();
}
log(s: string){
//log to a file and push into the stream
this._applicationLog$.next(s);
}
}
现在这是我的日志装饰器
var injector = ReflectiveInjector.resolveAndCreate([LocalStorageService, AppSettings]);
var service = <LoggerService>injector.resolveAndInstantiate(LoggerService);
var appSettings = <AppSettings>injector.resolveAndInstantiate(AppSettings);
function getTime() {
let now = new Date();
let min = ("00" + now.getMinutes()).substr(-2, 2);
let hours = ("00" + now.getHours()).substr(-2, 2);
return `${hours}:${min}`;
}
function log(message) {
service.log(`[${getTime()}] ${message}`);
}
export function Trace() {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
if (AppSettings.logSeverity !== LogSeverity.Trace) return;
log(`TRACE ${propertyKey}.enter()`);
};
}
现在我有一个阅读日志的组件
@Component({
templateUrl: 'applicationlogs.template.html'
})
export class ApplicationLogsPage implements OnInit {
logs: string[];
private subscription: Observable<string>;
constructor(private navCtrl: NavController, private $loggerService: LoggerService) { }
ngOnInit(){
this.subscription = this.$loggerService.applicationLog$.subscribe((s) => {
this.logs = s.split(/\r\n|\r|\n/g);
});
}
}