Home > Net >  BehaviorSubject In Angular making schedule (or timer) between data
BehaviorSubject In Angular making schedule (or timer) between data

Time:12-17

Iam trying to make a schedule update for my page

like "subscribe" and "unsubscribe" repeatedly with

to make page update after 10 muntes or so and in the same time not makeing a headinc on the DataBase

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { MaintenanceServicesService } from './MaintinanceService/maintenance-services.service';



@Component({
  selector: 'app-maintenance',
  templateUrl: './maintenance.component.html',
  styleUrls: ['./maintenance.component.scss']
})
export class MaintenanceComponent implements OnInit, OnDestroy {

  pageCards: any[] = []
  subscripe?: Subscription


  constructor(private _MaintenanceServicesService: MaintenanceServicesService) {
  }

  ngOnInit(): void {
    this.subscripe = this._MaintenanceServicesService.pageCards.subscribe({
      next: () => {
        this.GetPageCards()
      }
    });
  }

  ngOnDestroy(): void {
    if (this.subscripe) {
      this.subscripe.unsubscribe()
    }
  }

  GetPageCards() {
    this._MaintenanceServicesService.GetServicesPageCards()
    this.pageCards = this._MaintenanceServicesService.pageCards.getValue()
  }

}

CodePudding user response:

The title is misleading. BehaviorSubject will emit values whenever your data appears.

You don't need to subscribe/unsubscribe from data every time interval, that's the whole goal of observables - you react on data whenever it appears.

In the example you can find how there is timer that creates observable, that has some initialDelay (you can set it to 0) and after that delay it uses interval value to define the time between emitted events. So now you have a stream, that emits something every interval value, and here you want to do something - so you're fetching the data from your service and return it.

Another thing - don't need to subscribe/unsubscribe, just assign the result to data$ variable (it's observable) and in the template you can use the | async pipe, so it will handle subscription/unsubscription automatically.

  • Related