【发布时间】:2019-07-18 16:46:00
【问题描述】:
我有一个消息服务,用于在各种组件之间进行交互。当我点击Mine 按钮时,我只想触发一条消息。到目前为止,这有效。但是当我单击< 和> 按钮时,它会触发getMessage(),以便将值相加。但是当我点击Mine 时,我只想发送一个值。仅最后一个值。点击<和>时如何防止触发getMessage()?
当我点击<和>时,它会在卡片之间从1切换到10。当我点击Mine时,它应该只取我所在的卡片并将信息从该块发送到另一个组件。但相反,当我单击 < 或 > 时,getMessage() 被调用,它会将所有卡片加起来,直到我单击 Mine。我该如何防止呢?
遵循一些代码。我尽量保持紧凑:
消息服务.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();
}
矿工卡组件:
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.
});
}
当我点击<和>时,这些函数被调用:
根据 minerCounter 的值,显示卡 1-10。
precedingBlock() {
this.minerCounter--;
if (this.minerCounter < 1) {
this.minerCounter = 10;
}
}
nextBlock() {
this.minerCounter++;
if (this.minerCounter > 10) {
this.minerCounter = 1;
}
}
带有<和>按钮的卡片的外观:
Mine 按钮:
【问题讨论】:
-
take(1) 运算符将解决您在订阅中使用的问题
-
您还可以添加单击
<或>时调用的函数吗?
标签: angular typescript subscription