将服务用于其他服务

时间:2017-11-07 23:47:02

标签: angular service

我为自定义确认对话框编写了一个服务,用于从数据库和页面中删除项目。我还有另一项CRUD操作服务。 我的确认服务:

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

在我的组件中:

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

和deleteContent函数:

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

问题是当我调用confirmDeleteContent函数时,我在控制台中给出了这个错误:

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

我该如何处理? 谢谢!

0 个答案:

没有答案