我有一个消息服务,在各种组件之间进行交互。当我点击Mine
按钮时,我只想触发一条消息。这项工作到目前为止。但是当我点击<
和>
button时,它会触发getMessage()
,这样它就会增加值。但是当我点击Mine
时,我只想发送一个值。最后一个值。当点击getMessage()
and <
时,如何防止触发>
?
当我点击<
and >
it从1到10之间切换时。当我点击Mine
时,它应该只接受我所在的卡并将该块中的信息发送到另一个组件。但相反,当我点击<
or >
,getMessage()
is被调用,它加起来所有卡,直到我点击Mine
。我该如何预防呢?
遵循一些代码。我试着保持紧凑:
消息service.ts:
@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
getMessage(): Observable<any> {
console.log('Get Message Message Service');
return this.subject.asObservable();
}
矿工-card.component:
message: any;
subscription: Subscription;
constructor(private ref: ChangeDetectorRef, private emitTransactionService: EmitTransactionService,
private messageService: MessageService) {
this.subscription = this.messageService.getMessage().subscribe(message => {
console.log('Constructor miner-card'); // gets called multiple times, depending on how often I click < and >. When I click 10 times on < or > it will call this subscription 10 times.
});
}
当我点击<
and >
时,这些函数被调用:根据minerCounter的值,显示卡1-10。
precedingBlock() {
this.minerCounter--;
if (this.minerCounter < 1) {
this.minerCounter = 10;
}
}
nextBlock() {
this.minerCounter++;
if (this.minerCounter > 10) {
this.minerCounter = 1;
}
}
<
and >
buttons卡的外观如何:
Mine
按钮:
你应该总是在unsubscribe
ngOnDestroy
订阅。
message: any;
subscription: Subscription;
constructor(private ref: ChangeDetectorRef, private emitTransactionService: EmitTransactionService,
private messageService: MessageService) {
this.subscription = this.messageService.getMessage().subscribe(message => {
console.log('Constructor miner-card'); // gets called multiple times, depending on how often I click < and >. When I click 10 times on < or > it will call this subscription 10 times.
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
检查您的订阅是否未定义。如果未定义,则仅订阅。
constructor(
private ref: ChangeDetectorRef,
private emitTransactionService: EmitTransactionService,
private messageService: MessageService
) {
if (!this.subscription) {
this.subscription = this.messageService.getMessage().subscribe(message => {
console.log('Constructor miner-card'); // gets called multiple times, depending on how often I click < and >. When I click 10 times on < or > it will call this subscription 10 times.
});
}
}
在你的miner-card.component.ts
文件中使用take(1)
。这将只从订阅中获得单个数据。
message: any;
subscription: Subscription;
constructor(private ref: ChangeDetectorRef, private emitTransactionService: EmitTransactionService,
private messageService: MessageService) {
this.subscription = this.messageService.getMessage().pipe(take(1)).subscribe(message => {
console.log('Constructor miner-card'); // gets called multiple times, depending on how often I click < and >. When I click 10 times on < or > it will call this subscription 10 times.
});
}
希望这会有所帮助!