Search code examples
angularnotificationsangular-httpclient

Need to reload browser to see notification length


I am making a notification and i have a "bell" icon that has a badge. That badge shows how many notification i have. I determine by array length. My problem is that i need to reload the browser just to see the update of new notifications. I can only see the changes in the badge when i reload the browser. Is there anything missing in my code?

TS

ngOnInit() {
    this.getAllNotifs();
  }

  getAllNotifs(){
    this.notificationsService.getAll()
    .subscribe(
      (data:any) => {
        console.log(data);
        this.notifications = data.notifications;
      },
      error => {
        console.log(error);
      });
  }

HTML

 <i class="bell"></i>
 <span class="badge" *ngIf="notifications?.length>0">{{notifications.length}}</span>

Solution

  • At the moment, you're only making the HTTP once, in ngOnInit.

    Instead, if you want it to update, you'll need to set up polling.

    To do this, you can make use of setTimeout to call the function recursively, like so:

      timeout: Number;
    
      ngOnInit() {
          this.getAllNotifs();
      }
    
      ngOnDestroy() {
          // Clear the pending timeout so it doesn't keep running
          clearTimeout(this.timeout);
      }
    
      getAllNotifs(){
         this.timeout = setTimeout(() => {
            this.notificationsService.getAll()
            .subscribe(
              (data:any) => {
                console.log(data);
                this.notifications = data.notifications;
                // Call recursively
                this.getAllNotifs();
              },
              error => {
                console.log(error);
              });
         }, 5000);
      }