在Angular 7中,你可以使用RxJS库来实现Emitter和Poller的功能。下面是一个示例代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription, interval } from 'rxjs';
import { takeWhile } from 'rxjs/operators';
@Component({
selector: 'app-emitter-poller',
template: `
Angular 7 - Emitter and Poller
`,
})
export class EmitterPollerComponent implements OnInit, OnDestroy {
private emitterSubscription: Subscription;
private pollerSubscription: Subscription;
private emitterInterval = 1000;
private pollerInterval = 2000;
private isEmitterRunning = false;
private isPollerRunning = false;
ngOnInit() {}
ngOnDestroy() {
this.stopEmitter();
this.stopPoller();
}
startEmitter() {
if (!this.isEmitterRunning) {
this.isEmitterRunning = true;
this.emitterSubscription = interval(this.emitterInterval).subscribe(() => {
this.emitData();
});
}
}
stopEmitter() {
if (this.isEmitterRunning) {
this.isEmitterRunning = false;
this.emitterSubscription.unsubscribe();
}
}
startPoller() {
if (!this.isPollerRunning) {
this.isPollerRunning = true;
this.pollerSubscription = interval(this.pollerInterval)
.pipe(takeWhile(() => this.isPollerRunning))
.subscribe(() => {
this.pollData();
});
}
}
stopPoller() {
if (this.isPollerRunning) {
this.isPollerRunning = false;
this.pollerSubscription.unsubscribe();
}
}
emitData() {
// 发送数据的逻辑
console.log('Data emitted');
}
pollData() {
// 轮询数据的逻辑
console.log('Data polled');
}
}
在上面的示例中,我们使用了RxJS的interval函数来定时发送数据和轮询数据。startEmitter和startPoller方法分别启动了Emitter和Poller的功能,stopEmitter和stopPoller方法停止了它们。emitData和pollData方法是具体的数据发送和轮询逻辑,你可以根据自己的需求进行定制。
请注意,在组件销毁时,我们调用了ngOnDestroy方法来停止Emitter和Poller,这是为了避免内存泄漏。