需要重新加载浏览器才能看到通知长度

Need to reload browser to see notification length

我正在发出通知,我有一个带有徽章的 "bell" 图标。该徽章显示我有多少通知。我根据数组长度确定。我的问题是我需要重新加载浏览器才能看到新通知的更新。当我重新加载浏览器时,我只能看到徽章的变化。我的代码中是否缺少任何内容?

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>

目前,您只在 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);
  }