更新变量后如何触发从本地存储获取数据?角度的

时间:2020-07-18 20:06:48

标签: javascript angular

所使用的数据已更新-然后将其执行给我。

更好地解释问题:

登录组件获取

1 个答案:

答案 0 :(得分:1)

在分配了this.userInfo = JSON.parse(localStorage.getItem("userInfo"));之后,我还是不完全理解问题或分配data。尽管如此,API调用是异步的。要在API响应后做出任何声明,您需要将其包括在订阅回调中。您可以了解有关异步数据here的更多信息。

getUserInfo() {
  this.subscription.push(
    this.userService.getInfo().subscribe(
      data => {
        if(data) {
          this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
        }
      },
      err => {
        console.log(err)
      }
    )
  );
}

也许您可以提供更多详细信息,那么subscription数组也可以删除。相反,您可以使用RxJS takeUntil运算符关闭打开的订阅。

completed$ = new Subject<any>();

getUserInfo() {
  this.userService.getInfo().pipe(
    takeUntil(this.completed$)       // <-- complete when `completed$` emits
  ).subscribe(
    data => {
      if(data) {
        this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      }
    },
    err => {
      console.log(err)
    }
  );
}

ngOnDestroy() {
  this.completed$.next();            // <-- emit here to close active subscriptions
  this.completed$.complete();
}
相关问题