2017-01-25 4 views
0

関数からサービスにアクセスできません()else条件があります。ブラウザ端末に表示されるのは、 "TypeError:this._hitoService is undefined"です。 else条件が実行されると、サービスを使用してデータを取得する必要があります。どのように私はそれについて行くことができますか?関数からangle2サービスにアクセスできません

@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

@OdysseasIntannou TypeScriptの大きな点は、JavaScriptのようにする必要がないことです。そうではありません。 – PierreDuc

+0

"矢印機能は、JavaScript関数を書くための新しいES6構文です。開発者の時間を節約し、機能範囲を簡素化します。" typescript機能ではありません –

関連する問題