2017-01-25 84 views
0

无法从函数()中访问我的服务我在else条件中有..我在浏览器终端中得到的是“TypeError:this._hitoService is undefined”。当else条件执行时,我需要使用服务来获取数据。我怎么去解决它?无法从函数访问angular2服务

@Component({ 
    selector: 'app-time-line', 
    templateUrl: './time-line.component.html', 
    styleUrls: ['./time-line.component.css'], 
    providers: [HitoService], 
    entryComponents: [FormHitoComponent] 
}) 
export class TimeLineComponent implements OnInit, OnChanges { 
    @Input() calbuscador: String; 

nom_cal1: any; 
hito1: IHito[]; 
    hito: any; 

    constructor(private _hitoService: HitoService) { } 

    ngOnInit() { 


} 

ngOnChanges(){ 
     if (typeof this.calbuscador === "undefined"){ 
      swal("Atencion!", "Busca un calendario con el buscador del Side Menu", "error") 
     } 
     else{ 
     this.nom_cal1 = this.calbuscador; 
      swal({ 
       title: "Are you sure?", 
       text: "Se cargara el calendario : " + this.calbuscador, 
       type: "warning", 
       showCancelButton: true, 
       confirmButtonColor: '#DD6B55', 
       confirmButtonText: 'Yes, I am sure!', 
       cancelButtonText: "No, cancel it!", 
       closeOnConfirm: false, 
       closeOnCancel: false 
      }, function(isConfirm) { 
       if (isConfirm) { 
        swal({ 
         title: 'Cargando timeline!', 
         text: 'Cargando el Calendario en el Timline con sus hitos!', 
         type: 'success' 
        }, function() { 
          this._hitoService.getHitos() 
          .subscribe(hito1 =>{ 
          this.hito1 = hito1 
          console.log(this.hito1); // defined! 
          console.log("nomcal1" + this.nom_cal1); 
          if (typeof this.nom_cal1 === "undefined"){ 
           swal("Atencion!", "Busca un calendario con el buscador del Side Menu") 
          }else{ 
          drawtimeline1_1(this.hito1, this.nom_cal1); 
          } 
          }); 

        }); 

       } else { 
        swal("Cancelled", "No se cargara el Timeline :)", "error"); 
       } 
      }); 
     } 



} 

回答

2

很多例子在那里都有相同的问题。经验法则,绝对不要在TypeScript的课程中使用function关键字。这将取代this上下文与当前函数范围的上下文。始终使用() => {}符号:

swal({ 
     ... 
}, (isConfirm) => { 

}); 
+1

或定义一个变量来看待“这个”出来的功能(例如让_self =这一点。),并使用_self的功能。 –

+1

@OysysasIoannou关于TypeScript的一件大事就是你不必像JavaScript那样做。所以不,不这样做 – PierreDuc

+0

“箭头函数是用于编写JavaScript函数的新ES6语法,它们将节省开发人员的时间并简化函数范围”不是打字稿功能 –