Mic*_*ael 5 subscription typescript angular
我有一个消息服务,用于在各个组件之间进行交互。我只想在单击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();
}
Run Code Online (Sandbox Code Playgroud)
矿工卡.组件:
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.
});
}
Run Code Online (Sandbox Code Playgroud)
当我单击<和 时>,将调用这些函数: 根据 minerCounter 的值,将显示卡 1-10。
precedingBlock() {
this.minerCounter--;
if (this.minerCounter < 1) {
this.minerCounter = 10;
}
}
nextBlock() {
this.minerCounter++;
if (this.minerCounter > 10) {
this.minerCounter = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
<带有和按钮的卡片看起来如何>:
按钮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();
}
Run Code Online (Sandbox Code Playgroud)