0

I used a countdown timer solution from this example: Stackblitz --- It is from accepted answer of this question.

The difference is I don't use html input to reset my timer but Websocket message like this (the switch is the difference):

turn-timer.directive.ts:

@Directive({
  selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {

  private counter$ = new Subject<any>();
  private countSub$: SubscriptionLike;

  @Input() counter: number;
  @Input() interval: number;
  @Output() value = new EventEmitter<number>();

  constructor(private client: ClientService)
  {

    this.countSub$ = this.counter$.pipe(
      switchMap((options: any) =>
        timer(0, options.interval).pipe(
          take(options.count),
          tap(() => this.value.emit(--options.count))
        )
      )
    ).subscribe();

    this.client.messages.subscribe(msg =>
    {
      switch (msg.SUBJECT)
      {
        case 'TT_UPDATE':
        {
          this.counter = msg.COUNTER;
        }
        break;
        default:
        break;
      }
    });
  }

  ngOnChanges() {
    this.counter$.next({ count: this.counter, interval: this.interval });
  }
  ngOnDestroy() {
    this.countSub$.unsubscribe();
  }
}

That did not reset timer at all so I tried sending the message to initial component but that reseted timer only the first time it was sent.

turn-timer.component.ts:

@Component({
  selector: 'app-turn-timer',
  templateUrl: './turn-timer.component.html', 
  styleUrls: ['../../../../angry_styles.css']
})

export class TurnTimerComponent implements OnInit
{
    public counter : number = 60;
    interval = 1000;
    public current_player: string;

    constructor (private ll: LL, private client: ClientService, private players: PlayersInfo)
    {
        this.client.messages.subscribe(msg =>
        {
            switch (msg.SUBJECT)
            {
                case 'TT_UPDATE':
                {
                    this.counter = msg.COUNTER;
                    this.current_player = msg.PLAYER_ON_TURN;
                }
                break;
                default:
                break;
            }
        });
    }
    ngOnInit(): void {}
}

There is the html:

<ng-container [counter]="counter" [interval]="interval" (value)="value = $event">
    <span>{{ value }}</span>
</ng-container>

The original author of the answer had

<input type="number" [(ngModel)]="counter"/>

in his html and every time value of this

<input>

changed, the countdown timer was reseted to that value. However in my app it should be reseted by C# server that sends Websocket messages.

So what result I expect: On every "TT_UPDATE" message I expect the {{ value }} in HTML to change to the value of msg.COUNTER. The this.counter$.pipe then decrements {{value}}. That is working fine. Just the reseting part does not work.

Btw. Every message was received successfully, I checked the names of the fields. Here is definition of messages:

export interface Message {
  SUBJECT: string;
  COUNTER?: number;       // This is the problematic field.
  PLAYER_ON_TURN?: string;
}

@Injectable()
export class ClientService
{
  public messages: Subject < Message > ;

  constructor(wsService: WebsocketService) {
    this.messages = < Subject < Message >> wsService
      .connect(CHAT_URL).pipe(
        map((response: MessageEvent): Message => {
          console.log(response);
          const data = JSON.parse(response.data);
          return data;
      }), share());
  }

I deleted imports and paths from the code so it is shorter but they are correct. Also no errors in browser console were found.

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33

1 Answers1

0

In the end, I found out the solution myself. I didn't even need this.counter for this. I modified what happens after receiving the message:

this.client.messages.subscribe(msg =>
{
  switch (msg.SUBJECT)
  {
    case 'TT_UPDATE':
    {
      this.ResetTimer(msg.COUNTER);    // THIS IS NEW !!!
    }
    break;
    default:
    break;
  }
});

}

Then I created a new method that resets the countdown timer to value received from the message:

ResetTimer(updatedValue: number)
  {
    this.counter$.next({ count: updatedValue, interval: this.interval });
  }

As I don't change the interval I let it be the same. Sometimes I wonder how things are easy.

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33