避免在任何地方订阅

时间:2017-09-11 16:13:20

标签: angular rxjs

我正在开发一个必须调用很多不同WS的ap。 WS响应将在几个地方使用。 问题是我开始在各处获得大量的subscribe()。

服务的一个例子:

public getAllNotifications(): Observable<Notification[]> {
  return this.http.get(config.ws_url + `/api/user/notification/all`)
      .map((res: Response) => {
        return res.json();
      })
      .map((json) => {
        return plainToClass(Notification, json);
      }).share();
}

然后,每次我想使用此通知列表时,我都必须订阅()。

我的通知组件是:

  constructor(private notifService: NotificationService) {
    super();

    this.notifService.getAllNotifications().subscribe(notif => {
      this.notifications = notif;
    });
  }

  ngOnInit() {
  }

  private deleteNotif(notif: Notification): void {
    this.notifService.deleteNotification(notif.getId()).subscribe(json => {
      if (json.status === 200) {
        this.notifications.splice(this.notifications.findIndex(curNotif => curNotif.getId() === notif.getId()), 1);
      }
    });
  }

我认为这是一个问题,因为我认为我不应该订阅这么多,但是看不到这种方式。 有什么想法或链接可以解释使用它的好方法吗? THX

0 个答案:

没有答案
相关问题