Search code examples
javascriptangularangularjs-service

Unable to access angular2 services from a function


Can't access my service from the function() I have inside the else condition.. All I get is in the browser terminal is "TypeError: this._hitoService is undefined". I need to get the data using the services when the else condition is executed. How can I go about it?

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



 }

Solution

  • Lots of examples out there with the same issue. Rule of thumb, never use the function keyword inside your classes with TypeScript. This will replace the this context with that of the current function scope. Always use the () => {} notation:

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