AngularJS $ LocalStorage已清除,但setInterval仍然有效

时间:2019-05-23 05:15:52

标签: angularjs

我的代码段存在问题,它的工作原理就像我更新了选项卡中的任何内容一样,另一个选项卡也应该更改(调用GET函数)

在这种情况下,我的代码片段效果很好,在这里,请使用我的代码片段:

$scope.updateContact = function (contact) {
    $http.put('http://127.0.0.1:8000/api/v1/contact/' + $scope.clickedContact.id + '/?=format=json', $scope.clickedContact)
    .then(function(response){
      $scope.successEdit = 'You have updated the contact successfully';
      $scope.getAllContact(); // this function will make sure to reload the page after edit
      $localStorage.editedData = response.data;
      $scope.editedID = $localStorage.editedData.id;
      if (response.data.id == $localStorage.editedData.id) {
        $localStorage.isChanged = true;
      }
      $timeout(function(){
        $scope.successEdit = '';
      },4000);
    }, function(response){
      var errorData = response.data;
      $scope.errorEdit = Object.values(errorData)[0][0];
      $timeout(function(){
        $scope.errorEdit = '';
      }, 5000);
    });
  };


  setInterval(function() {
    if ($localStorage.isChanged == true) {
      $scope.getAllContact();
      localStorage.clear();
    }
  }, 5000);

希望您在代码段的末尾看到一个setinterval:

setInterval(function() {
    if ($localStorage.isChanged == true) {
      $scope.getAllContact();
      localStorage.clear();
    }
  }, 5000);

问题,

我想要本地存储更改时,使它调用此函数$scope.getAllContact();,此后,它应该清除localstorage,它可以工作,但问题是,即使清除了本地存储,它也可以连续工作。

我想在下面这样:

  1. 更改本地存储数据后,应调用此功能$scope.getAllContact();,然后清除本地存储。并且即使以后发生另一个更改,函数$scope.getAllContact();也会再次执行,然后再次清除,但是问题是它现在正在执行并清除,即使它不等待另一个更改发生,它也仅在一个更改后就继续执行发生。

1 个答案:

答案 0 :(得分:1)

采用变量

var clearInterval = setInterval(function() {
    if ($localStorage.isChanged == true) {
      $scope.getAllContact();
      localStorage.clear();
    }
  }, 5000);

并像这样清除

clearInterval(clearInterval);