2017-07-10 69 views
0

所以問題如下。我用Sweet Alert做了AlertService。我需要確認用戶是否確定刪除然後執行它。我有麻煩的回調上下文切換eventhough我使用箭頭函數,也嘗試過bind()。下面的代碼:Sweet Alert確認,然後在角2中執行刪除

AlertService

/** 
* This is a generic confirmation alert. 
* @param object the object with properties to be displayed. 
* @return {boolean} if confirmed, true, else null. 
* 
* For e.g. To generate an warning for example pass 'warning' in type attribute. 
*/ 
confirmAlert(object: any, callback: Function): any { 
    swal({ 
     title: object.title, 
     text: object.text, 
     type: object.type, 
     showCancelButton: true, 
     confirmButtonColor: '#3085d6', 
     cancelButtonColor: '#d33', 
     confirmButtonText: 'OK' 
    }).then(function (res) { 
     swal({ 
      title: object.confirmTitle, 
      text: object.confirmText, 
      type: 'success' 
     }); 
     return callback(true); 
    }, function (cancel) { 
     swal({ 
      title: 'Cancelled', 
      text: 'Action cancelled', 
      type: 'error' 
     }) 
     return callback(null); 
    }); 
} 

UsersComponent

/** 
* Deletes the selected user. Displays an alert to confirm. 
* Refreshes the current users array that is displayed in a table.. 
*/ 
deleteUser() { 
    let usersToDelete = { 
     'users': this.users 
    }; 
    this.alertService.confirmAlert(this.createMessages.alert.delete, (confirm) => { 
     if (confirm) { 
      this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => { 
       if (res.status == 200) { 
        this.alertService.okAlert(this.createMessages.alert.deleteSuccess); 
       } 
      }); 
     } 
    }); 
    this.refreshUsers(); 
} 

的問題是,包含選定的用戶從來沒有對象到達web服務。我console.logged一切,並談到這個問題,我不知道如何解決。

回答

0

的問題是我有refreshUsers()回調之外,我沒有意識到這是我的擦除this.users

/** 
* Deletes the selected user. Displays an alert and refreshes the current array. 
*/ 
deleteUser() { 
    let usersToDelete = { 
     'users': this.users 
    }; 
    this.alertService.confirmAlert(this.allMessages.alert.delete, (res) => { 
     if (res) { 
      this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => { 
       if (res.status == 200) { 
        this.refreshUsers(); 
       } 
      }); 
     } 
    }); 
} 


/** 
* This method is used to refresh the current displayed users table. 
* Select a user and it's index. 
* Delete it from this.all array. 
* Delete it from this.users array. 
* Call this.getAllUsers() to refresh the array. 
*/ 
refreshUsers() { 
    while (this.users.length > 0) { 
     this.all.forEach(element => { 
      let i = this.users.indexOf(element._id); 
      if (i != -1 && this.users.length >= 0) { 
       let e = this.all.indexOf(element); 
       this.all.splice(e, 1); 
       this.users.splice(i, 1); 
       this.getAllUsers(); 
      } 
     }); 
    } 
}