Search code examples
angulartypescriptasync-awaitangular-httpclient

In angular, Subscribe function is called after all methods are called in the the component, this results that I am unable to use the response


I have tried to solve it with await and async, but as being new to typescript I am not used to these methods. I have used await and async like this:

async refreshList(){
 await this.service.refreshList().subscribe(res => {
   console.log(res);
   this.service.todoListModel=res;
   });
}

I get to know that subscribe method parameter codes are last to execute by debugging and console output. please help in amending my below component code :

import { Component, OnInit } from '@angular/core';
import { groupBy } from '@progress/kendo-data-query';
import { moveDown, slideIn, slideOut } from '../animations';
import { TodoService } from '../todo.service';

@Component({
  selector: 'todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css'],
  providers: [TodoService],
  animations: [
    trigger('todoAnimations',[
      transition(':enter',[
        group([
          query('h1', [
            useAnimation(moveDown)
          ]),
          query('input', [
            useAnimation(moveDown)
          ]),
          query('@todoItem', [
            stagger(125, animateChild())
          ]),
        ])
      ])
    ]),
    trigger('todoItem', [
      transition(':enter', [
        useAnimation(slideIn)
      ]),
      transition(':leave',[
        useAnimation(slideOut)
      ])
    ])
  ]
})
export class TodoComponent implements OnInit {
  
  constructor(public service:TodoService) {
    this.refreshList(); 
    console.log(this.service.todoListModel);
    
  }
  
  ngOnInit(): void {
    this.organizeTodosByHour();
  }
    refreshList(){
      this.service.refreshList().subscribe(res => {
        console.log(res);
        this.service.todoListModel=res;
        });
    }
  organizeTodosByHour(){
    do
    {
      if(!this.service.todos) return null;
      this.service.hourlyTodos=groupBy(this.service.todos,[{field: "hour"}]);

      console.log(JSON.stringify(this.service.hourlyTodos,null,2));
      return 0;
    }
    while(this.service.todoListModel===[])
  }
  public onTimeChange(t:any){
    t.hour=t.due.getHours();
    this.organizeTodosByHour();
    console.log(this.service.todos,this.service.hourlyTodos);
  }
  addTodo(input: HTMLInputElement){
    this.service.todos=[{item:input.value, due: new Date(), hour:(new Date()).getHours()},...this.service.todos];
    input.value='';
    this.organizeTodosByHour();
  }
  removeTodo(i:number){
    this.service.todos.splice(i,1);
    this.organizeTodosByHour();
  }
}

please help me by giving me the fix to my problem. It will very helpful if anyone can explain to me how to use await and async.


Solution

  • Thank you guys for your efforts, Atlast I did understand await and async methods and I ended up with the code below:

    import { animateChild, group, query, stagger, transition, trigger, useAnimation } from '@angular/animations';
    import { Component, OnInit } from '@angular/core';
    import { groupBy } from '@progress/kendo-data-query';
    import { moveDown, slideIn, slideOut } from '../animations';
    import { TodoService } from '../todo.service';
    import { lastValueFrom } from 'rxjs';
    
    @Component({
      selector: 'todo',
      templateUrl: './todo.component.html',
      styleUrls: ['./todo.component.css'],
      providers: [TodoService],
      animations: [
        trigger('todoAnimations',[
          transition(':enter',[
            group([
              query('h1', [
                useAnimation(moveDown)
              ]),
              query('input', [
                useAnimation(moveDown)
              ]),
              query('@todoItem', [
                stagger(125, animateChild())
              ]),
            ])
          ])
        ]),
        trigger('todoItem', [
          transition(':enter', [
            useAnimation(slideIn)
          ]),
          transition(':leave',[
            useAnimation(slideOut)
          ])
        ])
      ]
    })
    export class TodoComponent implements OnInit {
      
      constructor(public service:TodoService) {
        this.refreshList(); 
        
      }
      
      ngOnInit(): void {
      }
    
      async refreshList(){
        const list$ = this.service.refreshList();
        this.service.todoListModel= await lastValueFrom(list$);
        console.log(this.service.todoListModel);
        this.service.todoListModel.forEach(element => {
          this.service.todos.push({item:element.itemName as string,due:(new Date(element.dueDate)),hour: (new Date(element.dueDate)).getHours()});
        });
        this.organizeTodosByHour();
    }
    
      organizeTodosByHour(){
        if(!this.service.todos) return null;
          this.service.hourlyTodos=groupBy(this.service.todos,[{field: "hour"}]);
          console.log(JSON.stringify(this.service.hourlyTodos,null,2));
          return 0;
      }
    
      public onTimeChange(t:any){
        
        t.hour=t.due.getHours();
    
        this.organizeTodosByHour();
        console.log(this.service.todos,this.service.hourlyTodos);
        
      }
    
      addTodo(input: HTMLInputElement){
        this.service.todos=[{item:input.value, due: new Date(), hour:(new Date()).getHours()},...this.service.todos];
        input.value='';
        this.organizeTodosByHour();
      }
    
      removeTodo(i:number){
        this.service.todos.splice(i,1);
        this.organizeTodosByHour();
      }
    }