2017-07-10 38 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(); 
      } 
     }); 
    } 
}