在Angular中,单例服务是指在整个应用程序中只有一个实例的服务。如果您想将单例服务的更改传递给一个组件,可以使用事件或RxJS的Subject来实现。
以下是使用事件的示例:
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class MySingletonService {
public dataChanged: EventEmitter = new EventEmitter();
private data: any;
setData(data: any) {
this.data = data;
this.dataChanged.emit(this.data);
}
}
import { Component, OnInit } from '@angular/core';
import { MySingletonService } from './my-singleton.service';
@Component({
selector: 'app-my-component',
template: `
{{ data }}
`
})
export class MyComponent implements OnInit {
data: any;
constructor(private singletonService: MySingletonService) { }
ngOnInit() {
this.singletonService.dataChanged.subscribe((data: any) => {
this.data = data;
});
}
}
import { Component } from '@angular/core';
import { MySingletonService } from './my-singleton.service';
@Component({
selector: 'app-another-component',
template: `
`
})
export class AnotherComponent {
constructor(private singletonService: MySingletonService) { }
updateData() {
const newData = 'New data';
this.singletonService.setData(newData);
}
}
使用RxJS的Subject的示例:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class MySingletonService {
public dataChanged: Subject = new Subject();
private data: any;
setData(data: any) {
this.data = data;
this.dataChanged.next(this.data);
}
}
import { Component, OnInit } from '@angular/core';
import { MySingletonService } from './my-singleton.service';
@Component({
selector: 'app-my-component',
template: `
{{ data }}
`
})
export class MyComponent implements OnInit {
data: any;
constructor(private singletonService: MySingletonService) { }
ngOnInit() {
this.singletonService.dataChanged.subscribe((data: any) => {
this.data = data;
});
}
}
import { Component } from '@angular/core';
import { MySingletonService } from './my-singleton.service';
@Component({
selector: 'app-another-component',
template: `
`
})
export class AnotherComponent {
constructor(private singletonService: MySingletonService) { }
updateData() {
const newData = 'New data';
this.singletonService.setData(newData);
}
}
无论您选择使用事件还是RxJS的Subject,都可以将单例服务的更改传递给一个组件。