0

I wrote a service for a custom confirmation dialog for delete items from database and page. also i have an another service for the CRUD operations. my confirmation service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AlertService {
  subject = new Subject<any>();
  constructor() {}
  confirmThis(message: string, siFn: () => void, noFn: () => void, className) {
    this.setConfirmation(message, siFn, noFn, className);
  }
  setConfirmation(message: string, siFn: () => void, noFn: () => void,    className) {
    const that = this;
    this.subject.next({ type: 'confirm',
       text: message,
       siFn: function(){
          that.subject.next(); // this will close the modal
          siFn();
       },
       noFn: function(){
          that.subject.next();
          noFn();
       }
    });
  }
  getMessage(): Observable<any> {
     return this.subject.asObservable();
  }
}

and in my component:

confirmDeleteContent(id, i) {
const that = this;
this.alertService.confirmThis('Are you sure?', function(){
  alert('Yeap');
  that.deleteContent(id, i);
}, function(){ alert('No'); }, this);
}

and deleteContent function:

deleteContent(id, i) {
this.service.deleteContent(id)
  .subscribe(
    (response) => {
      this.contents.splice(i, 1);
      console.log(JSON.stringify(response));
    },
    (error) => {
      console.log(error);
    }
  );
}

the problem is when i call confirmDeleteContent function i give this error in console:

EXCEPTION: Error in ./AlertComponent class AlertComponent - inline template:16:14 caused by: this is undefined  error_handler.js:54
ORIGINAL EXCEPTION: this is undefined

How can i handle this? thanks!

omid nematollahi
  • 451
  • 4
  • 22
  • You can import one service into another (`@Injectable`) the same way you import a service in a `@Component`. Where do you define `this.service.deleteContent(id)`? That's the most likely spot this error is coming from, but we'd have to see line 16 in your HTML (and related items to that line) in order to help beyond that. – Z. Bagley Nov 07 '17 at 23:51
  • i defined this.service.deleteContent(id) in my related service as: deleteContent(content: any) { return this.http.delete('content_manage', content); } – omid nematollahi Nov 07 '17 at 23:57
  • use arrow function instead of `function` to preserve the `this` keyword. – AT82 Nov 10 '17 at 05:22

0 Answers0