簡體   English   中英

無法從功能訪問angular2服務

[英]Unable to access angular2 services from a function

無法從else條件中具有的function()訪​​問我的服務。.我在瀏覽器終端中得到的只是“ TypeError:this._hitoService is undefined”。 當執行else條件時,我需要使用服務獲取數據。 我該怎么辦?

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



 }

許多例子都存在相同的問題。 憑經驗,切勿在TypeScript的類內部使用function關鍵字。 這將用當前函數范圍的上下文替換this上下文。 始終使用() => {}表示法:

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM