1

我使用 angular 和SweetAlert2。在我想调用服务或确认后的任何函数或变量之前,我的 sweetalert2 工作得非常好。

我的组件:

import swal from 'sweetalert2';

@Component({
  selector: 'app-filter',
  templateUrl: './filter.component.html',
})
export class FilterComponent implements OnInit {

  private swal: any;

  constructor(private asyncService: AsyncService) {

  }

  ngOnInit() {
      this.getCurrentData(1);
  }

  getCurrentData(id: number) {
    this.asyncService.getCurrentFilterData(id)
      .subscribe(
        response => {
          this.filter = response.json();
        },
        error => console.log('error : ' + error)
      );
  }

  saveFilter() {
    swal({
      title: 'Are you sure?',
      text: 'You wish to save filter changes!',
      type: 'question',
      showCancelButton: true,
      confirmButtonText: 'Save',
      cancelButtonText: 'Cancel'
    }).then(function() {

      this.asyncService.filterUpdate(this.filter) // can't access to this. (this.filter or this.asyncService)
        .subscribe(
          response => {
              console.log('success');
          },
          error => console.log('error : ' + error)
        );
    });
  }

有什么解决方案我怎样才能访问这个?

4

1 回答 1

2

如果需要,使用箭头函数this将绑定到组件实例

.then(() => {

代替

.then(function() {
于 2017-10-02T09:24:10.137 回答