Angular variable returns undefined in some points of the controller but on others it returs his value

330 views Asked by At

Im working a controller where I get an array of values from a service. When I have the values from the service I set the value of a variable as the first element of that array then I do a console.log of that variable ans returns the value correctly. The problems comes when I try to use this value to do some operations then when I check the variable I get undefied and I can't understand why.

This is my code:

export class DetailTaskComponent implements OnInit {

  constructor(private taskService: TaskService, private route: ActivatedRoute, private authSservice: AuthService) { }

  // old variable
  taken = false;

  startButton = true;
  pauseButton = true;
  finishButton = true;

  task;
  ////////////////////////////

  // Trabajo con 2 tasks en este componente globalTask y userTask, la primera es la Task en general y la otra es lo que ha hecho el
  // usuario actual con esta Task.

  // Variable que guarda la Task de nivel global
  globalTask: Task;

  // Variable que guarda la Task a nivel del usuario actual
  userTask: UserTask;
  workingTask: UserTask;

  // Variable array de tipo UserTask, hay que usar un array porque aunqeu solo haya un registro
  usersTasks: UserTask[];

  // Esta función recupera la Task a nivel global a partir del parametro :id
  async getTask(id){
    console.log('getTask');
    this.globalTask = await this.taskService.getTask$(id).pipe(first()).toPromise();
  }

  // Si no hay información en el historial del usuario con esa Task creamos una entrada, aunque solo consulte la Task y no interactue
  async setTaskUserHistoric(set: UserTask){

    console.log(`Entro en la funcuión que deberia crear la entraea`);
    set.id = uuidv4();
    set.status = 'Pendent';

    this.workingTask = set;

    await this.taskService.setTaskHistoric(set);

  }

  // Esta función recupera lo que ha hecho el usario ya con la tare actual, si no ha trabajado nunca con ells
  // lo añade a la tabla, para cuando empìece a interactuar con ella no teneer que controlar que infromación hay que crear o guardar
  async getUserTask(update: UserTask){

    console.log('Antes de recuperar el array');

    this.usersTasks = await this.taskService.getHistoric(update).pipe(first()).toPromise();

    console.log(`Total de entradas encontradas: ${this.usersTasks.length}`);

    // Si el usuario ha trabajado alguna vez con la task, ni que sea solo consultarla, tendremos un registro, en caso contrario el array valdrá 0 y
    // habrá que crear una entrada
    if(this.usersTasks.length > 0){
      this.workingTask = this.usersTasks[0]; // Si existre u registro lo guardamos en la vraiable userTask, esta variable es la que guardara todo el progreso del usuario
      console.log('Se ha encontrado una entrada');
      console.log(this.workingTask);
    }
    else {
      this.setTaskUserHistoric(update); // Para crear el registro le paso los datos del usuario y de la task
      console.log(`No se ha encontrado ninguan entrada`);
    }

  }

  // Funciones para manipualr las Tasks
  startTask(){}
  pauseTask(){}
  finishTask(){}

  // Esta función congigura la botonera, por defecto todos los botones estan desactivados y en función del estado de la Task para el usuario
  // se activan o desactivan el boton de play/pause/finish.
  // Esta función no tiene parametros porque usa los variables de userTask;
  setKeypad(task){
    console.log(this.workingTask);
    console.log(task);
    // if(this.userTask.status === 'Pendent'){
    //   console.log(`El usuario nunca ha trabajado con la tarea`);
    // }
  }

  async ngOnInit(): Promise<void> {

    // Al cargar el componente recupero el parametro id de la url y lo paso a la función que recupera la task y la guarda en la globalTask
    await this.getTask(this.route.snapshot.paramMap.get('id'));

    // Ejecuto la función que valida si el usuario ya ha trabajado con la Task y que en cualquier caso informará la variable userTask para poder  guardar el progreso
    // Información mínima para encontrar el historial del usuario
    let check: UserTask = {
      id_task: this.globalTask.id,
      id_user: await this.authSservice.getUser()
    }

    console.log('Antes de revisar si el usario ya tiene una entrada en el user_task');
    this.getUserTask(check);

    // Configuramos la botonera
    this.setKeypad(this.workingTask);

  }

}

Resumin, on the onInit I call the function that get the list of values, asign the first element to the variable workingTask (at this moment the console.log) returns the value, but then when I enter into setKeypad() function I can't gread the workingTask variable as it return undefined.

1

There are 1 answers

0
buzatto On

getUserTask is an async function, so you have to await its execution to workingTask get properly set:

await this.getUserTask(check);

// Configuramos la botonera
this.setKeypad(this.workingTask);