Search code examples
angularsweetalertsweetalert2

Calling the the service or variable in the result of SweetAlert2 modal angular 2(4)


I use angular and SweetAlert2. My sweetalert2 is working perfectly fine until I want to call service, or whatever function or variable after confirm.

My component:

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)
        );
    });
  }

Is there any solution how can I access to this?


Solution

  • Use arrow function if you want that this will be bound to component instance

    .then(() => {
    

    instead of

    .then(function() {