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

Issue

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

If you want to use async/await, you can use convert observable to promise. There is a method which is being used, but deprecated toPromise instead use lastValueFrom.

import { lastValueFrom } from 'rxjs';

constructor(public service:TodoService) {
   (async () => {
         await this.refreshList();
         console.log(this.service.todoListModel);
   })();
  }

async refreshList(){
      const list$ = this.service.refreshList();
      this.service.todoListModel= await lastValueFrom(list$);;
}

There are other util observables function too for specific cases, you should check this link for more details.

Answered By – Apoorva Chikara

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published