需要重新加载浏览器以查看通知长度

时间:2018-07-22 11:39:02

标签: angular notifications angular-httpclient

我正在发出通知,并且我有一个带有徽章的“响铃”图标。该徽章显示了我有多少个通知。我由数组长度确定。我的问题是我需要重新加载浏览器才能看到新通知的更新。重新加载浏览器时,我只能看到徽章中的更改。我的代码中缺少任何内容吗?

  

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>

1 个答案:

答案 0 :(得分:1)

目前,您仅在ngOnInit中创建一次HTTP。

相反,如果要更新它,则需要设置轮询。

为此,您可以使用setTimeout来递归调用函数,如下所示:

  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);
  }